{"id":18573322,"url":"https://github.com/huawenyu/design-patterns-in-c","last_synced_at":"2025-04-05T04:14:28.315Z","repository":{"id":15768996,"uuid":"18507912","full_name":"huawenyu/Design-Patterns-in-C","owner":"huawenyu","description":"Practical design patterns in C","archived":false,"fork":false,"pushed_at":"2023-09-20T18:41:52.000Z","size":416,"stargazers_count":433,"open_issues_count":1,"forks_count":116,"subscribers_count":31,"default_branch":"master","last_synced_at":"2025-03-29T03:11:29.334Z","etag":null,"topics":["c","oop","patterns"],"latest_commit_sha":null,"homepage":null,"language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huawenyu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2014-04-07T06:12:51.000Z","updated_at":"2025-03-14T14:45:50.000Z","dependencies_parsed_at":"2025-02-10T00:00:46.098Z","dependency_job_id":null,"html_url":"https://github.com/huawenyu/Design-Patterns-in-C","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huawenyu%2FDesign-Patterns-in-C","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huawenyu%2FDesign-Patterns-in-C/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huawenyu%2FDesign-Patterns-in-C/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huawenyu%2FDesign-Patterns-in-C/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huawenyu","download_url":"https://codeload.github.com/huawenyu/Design-Patterns-in-C/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247284953,"owners_count":20913704,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","oop","patterns"],"created_at":"2024-11-06T23:08:58.295Z","updated_at":"2025-04-05T04:14:28.298Z","avatar_url":"https://github.com/huawenyu.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n**Table of Contents**  *generated with [DocToc](http://doctoc.herokuapp.com/)*\n\n- [Design-Patterns-in-C](#design-patterns-in-c)\n  - [C oop implement:](#c-oop-implement)\n- [](#)\n- [  member           -                +       +](#member-----------------------------------)\n  - [Quick Start:](#quick-start)\n  - [Make a pattern](#make-a-pattern)\n  - [Auto Generate class](#auto-generate-class)\n  - [OOP basic:](#oop-basic)\n    - [Object](#object)\n    - [Class](#class)\n    - [Data Abstraction \u0026 Encapsulation](#data-abstraction-\u0026-encapsulation)\n    - [Inheritance](#inheritance)\n    - [Polymorphism](#polymorphism)\n  - [Design Patterns:](#design-patterns)\n  - [Contribute](#contribute)\n  - [License](#license)\n  - [See also \u0026 References](#see-also-\u0026-references)\n  - [TODOS](#todos)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n# Design-Patterns-in-C\n\n**Practical Design Patterns in C**  \n\nThis will be a repository of\n* Implement the Design Patterns of **GoF**(Gang of Four) in C.  \n* (Version 1) Provide script to auto generate Design Patterns into different code style: C, pyNSource(ascii-UML), ... [C++, Java, C#]\n* (Version 2) Reference from [Design Patterns in PHP](https://github.com/kamranahmedse/design-patterns-for-humans)\n\n## C oop implement:\n\n```python\n\n======================================================\n                private protected public  static  pure\n-------------------+--------+-------+--------+-----+--\nconstructor        +                +       +\ndestructor\n  virtual                           +\nmethods\n  virtual                           +              +\n  routine          +                +       +\nvariables\n  member           -                +       +\n=================================================\n+ have implemented\n- can implemented with the \"handle/body\" idiom, but ...\n\n```\n\n## Quick Start:\n\n```sh\nMake a pattern\n--------------\n\n$ cd auto-gen\n$ make\n$ make runall\n$ make clean_all\n\nAuto Generate class\n-------------------\n\n$ cd tools\n$ python gencode.py --file json/prototype.json \u003e log   \u003c\u003c\u003c the generated code in dir ./tools/code/c/prototype\n\n```\n\n## OOP basic:\n\nThe oop come from myobj.h:\n* each class have it's special v-table, here is the struct ops\n* the derive class should also have it's v-table instance, but same type with it's parent\n* the derive class's v-table instance should initial with merge with it's parent\n\n### Object\n```c\nstruct shape_rectangle *rect;\n\nrect = malloc(sizeof(*rect));\nif (!rect) return -1;\nshape_rectangle_init(rect);\nshape_draw(\u0026rect-\u003eshape);\nshape_free(\u0026rect-\u003eshape);\n```\n\n### Class\n\n```c\nstruct shape_ops;\nstruct shape {\n\tstruct shape_ops *ops;\n\tstruct color * _color;\n};\nstruct shape_ops {\n\tvoid (*_destructor)(struct shape *);\n\tvoid (*free)(struct shape *);\n\tvoid (*draw)(struct shape *);\n\tstruct shape_ops *__super;\n};\nvoid shape_init(struct shape *);\n```\n\n### Data Abstraction \u0026 Encapsulation\n\n```c\nstruct shape_rectangle *rect;\n\nshape_rectangle_init(rect);\nshape_draw(\u0026rect-\u003eshape);\nshape_free(\u0026rect-\u003eshape);\n```\n\n### Inheritance\n\n```c\nstruct shape_rectangle {\n\tstruct shape shape;\n};\n\nvoid shape_rectangle_init(struct shape_rectangle *);\n```\n\n### Polymorphism\n\n```c\nstruct shape_rectangle *rect;\nstruct shape_circle *circle;\n\nshape_draw(\u0026rect-\u003eshape);\nshape_draw(\u0026circle-\u003eshape);\n```\n## Another OOP style (OOC by A.T. Schreiner)\n\n```c\n// file: OOC.h\nstruct Class {\n    size_t size;\n    void *(* ctor) (void *self, va_list *app);\n};\n\nvoid *new(const void *_class, ...) {\n    const struct Class *class = _class;     // assign the address of `struct String` class\n    void *p = calloc(1, class-\u003esize);       // allocate the sizeof(struct String);\n\n    assert(p);\n    *(const struct Class **)p = class;      // Force the conversion of p and set the argument `class` as the value of this pointer.\n    if(class-\u003ector) {\n        va_list ap;\n        va_start(ap, _class);\n        p = class-\u003ector(p, \u0026ap);        // Now what is `p` here, a `struct String` or `struct Class`.\n                                        // and if it is `struct Class` then how it convert to `struct String` in `String_ctor` function \n                                        // given below.\n        va_end(ap);\n    }\n    return p;\n}\n\n\n// file: mystring.h\n\n#include \"OOC.h\"\n\nstruct String {\n    const void *class;  // must be first\n    char *text;\n};\n\nstatic void *String_ctor(void *_self, va_list *app) {\n    struct String *self = _self;        \n    const char *text = va_arg(*app, const char *);\n\n    self-\u003etext = malloc(strlen(text) + 1);\n    assert(self-\u003etext);\n    strcpy(self-\u003etext, text);\n    return self;\n}\n\n// Initialization\nstatic const struct Class _String  = {\n    sizeof(struct String),\n    String_ctor\n};\n\nconst void *String = \u0026_String;\n\n\n\n// file: main.c\n\n#include \"mystring.h\"\n\nint main(void)\n{\n    void *a = new(String, \"some text\");\n}\n```\n\n## Design Patterns:\n\n* Using patterns can keep our code **loose coupling, cohesive code, and encapsulation**.\n* Then we can write maintainable code with a high degree of **Orthogonality**.\n\n1. Creational patterns\n  * Factory\n    - Static Factory\n    - Simple Factory\n    - Factory Method\n      + GoF\n      + two stage\n    - Abstract Factory\n      + GoF family objects\n      + two dimension\n      + three dimension\n  * Builder\n  * Prototype\n  * Singleton\n2. Structural patterns\n  * Adapter\n  * Bridge\n  * Composite\n  * Decorator\n  * Facade\n  * Flyweight\n  * Private Class Data\n  * Handle Body Idiom\n  * Proxy\n  * MVC\n3. Behavioral patterns\n  * Chain of Responsibility\n  * Command\n  * Interpreter\n  * Iterator\n  * Mediator\n  * Observer\n  * State\n  * Strategy\n  * Template Method\n  * Visitor\n\nThe repository contains a folder by each design pattern.\n\n## TODOS\n\noop:\nhttp://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep\nhttp://www.tutorialspoint.com/cplusplus/cpp_object_oriented.htm\nhttp://oopsconcepts.blogspot.ca/\n\n* python uml object support\n* manual about oop's basic principle\n* manual about oop C's implement:\n```\nops -\u003e vtable\n  t_ops -\u003e half class level vtable\ncaps -\u003e DI - callback (construct)\ncbs -\u003e DI - client/request callback (argument)\n\n```\n\n* [The SOLID principles of object-oriented programming](https://en.wikipedia.org/wiki/SOLID)\n  - DIP: Dependence Inversion Principle, dependence on abstract interface\n    - DI: [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection)\n    - AI: argument injection\n    - IoC: Inversion of Control\n      + Interface injection\n      + Constructor injection\n      + Setter injection\n      + Method injection\n  - LSP: Liskov Substitution Principle\n  - SRP: Single Responsibility Principle\n  - OCP: Open Close Principle\n  - ISP: Interface Segregation Principle\n  - LoD: Least Knowledge Principle\n\n* framework-lib cooperate with client:\n  - caps: template drive\n    + can be simple interface which implement by client and used by class, is callback-functions\n    + can be simple factory which implement by client and used by class to create itself, such as client's memory implements\n  - derive (instance embed): LSP, inheritance as-A\n  - client/request-cbs: AI,MI, one kind of client/request ops, \n  - call-ops: smaller client-ops\n \n\n## Contribute\n\nAll constructive comments are welcome.\nPlease feel free to fork and extend existing or add your own examples and send a pull request with your changes!\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Wilson Huawen Yu\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n## See also \u0026 References\n\n[PyNSource - UML tool for Python](http://www.andypatterns.com/index.php/products/pynsource/)\n[Design Patterns Explained Simply](http://sourcemaking.com/design_patterns)  \n[.NET Design Patterns](http://www.dofactory.com/Patterns/Patterns.aspx)  \n[Software design pattern](http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29)  \n[Computer Science Design Patterns](http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns)  \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuawenyu%2Fdesign-patterns-in-c","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuawenyu%2Fdesign-patterns-in-c","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuawenyu%2Fdesign-patterns-in-c/lists"}