C language and design patterns (inheritance, encapsulation, polymorphism)

Foreword

  We still remember the first C ++ university course when the teacher told us that, C ++ is an object-oriented language. C ++ has three important characteristics, i.e. inheritance, encapsulation, polymorphism. Wait until later increased with the accumulation of experience and coding, I slowly understand object-oriented meaning. However, so after my work, using the programming language C language is more, this time I want the C language can become object-oriented language do? Wait until later by thinking and practice, I find that the C language is also possible to object-oriented design patterns can be applied also, the key lies in how to achieve three important properties of object-oriented languages.

Succession

typedef struct _parent
{
    int data_parent;
 
}Parent;
 
typedef struct _Child
{
    struct _parent parent;
    int data_child;
 
}Child;

 When designing the C language inheritance, we need to do is to put data on the basis of the first position to inherit the structure. In this way, whether it is accessing data, strong transfer data, access to data will not have any problems.

Encapsulation

struct _Data;
 
typedef  void (*process)(struct _Data* pData);
 
typedef struct _Data
{
    int value;
    process pProcess;
    
}Data;

 Significance of encapsulation is that the functions and data are tied together, and data are tied together. In this way, we can have access to all the data through a simple pointer to a structure, through all functions. Encapsulation, which is owned by the class attribute, of course, the data structure of owned properties.

Polymorphism

typedef struct _Play
{
    void* pData;
    void (*start_play)(struct _Play* pPlay);
}Play;

 Polymorphic, that is to say with the same processing of different data interface code. For example, here's Play structure is a common data structure, we do not know what pData data, start_play what handler? However, when we are dealing simply call pPlay-> start_play (pPlay) on it. The remaining things we do not control, because different interfaces have different functions to deal with, we just have to learn to call it.

Published 259 original articles · won praise 6 · views 8094

Guess you like

Origin blog.csdn.net/qq_23929673/article/details/103538240