-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc_cheatsheet1.c
2828 lines (2363 loc) · 77.4 KB
/
c_cheatsheet1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* written by Nick Shin - [email protected]
* the code found in this file is licensed under:
* - Unlicense - http://unlicense.org/
*
* this file is from https://github.com/nickshin/CheatSheets/
*
*
* C is a pretty simple language.
* so, this file will describe design patterns in C, even though
* it is normally used with Object Oriented languages.
* - creational patterns
* - structural patterns
* - behavioral patterns
* - design principles
*
*
* to compile:
* gcc -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include \
* -L/usr/lib/ -lglib-2.0 c_cheatsheet1.c -o c_cheatsheet1
*
* to run:
* ./c_cheatsheet1
*
*
* best viewed in editor with tab stops set to 4
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/* DESIGN PATTERNS NOTES {{{
design patterns represents:
---------------------------
o shared vocabulary
i.e. a label to describe the common patterns
o solutions (patterns) to common problems (requirements)
o instead of code reuse, you get experience (patterns) reuse
o thinks about how to create flexble (pattern) designs that
are maintainable and that can cope with change
o API: program to an interface, not an implementation
i.e. program to a supertype
o encapsulate what varies
o favor composition over inheritance (programming language masturbation)
o depend on abstraction, not on concrete classes
o strive for loosely coupled designs between objects that interact
the details:
------------
http://www.codeguru.com/forum/showthread.php?t=327982
-----------------------------------------------------------
| purpose |
-----------------------------------------------------------
| creational | structural | behavioral |
-----------------+------------------+------------+--------------------------
| | class | factory method | adapter | interpreter |
| | | | | template method |
| |--------+------------------+------------+--------------------------
| | | abstract factory | bridge | chain of responsibility |
| | | builder | composite | command |
| | | prototype | decorator | iterator |
| scope | | singleton | façade | mediator |
| | object | object pool | flyweight | memento |
| | | | proxy | observer |
| | | | | state |
| | | | | strategy |
| | | | | visitor |
| | | | | null object |
----------------------------------------------------------------------------
class: compile time
object: run time
Creational Patterns: initializing and configuring classes and objects
Structural Patterns: decoupling the interface and implementation of classes and objects
Behavioral Patterns: dynamic interactions among societies of classes and objects
creational
- factory method : Creates an instance of several derived classes
- abstract factory : Creates an instance of several families of classes
- builder : Separates object construction from its representation
- prototype : A fully initialized instance to be copied or cloned
- singleton : A class of which only a single instance can exist
- object pool : Reuses and shares objects that are expensive to create
structural
- adapter : Match interfaces of different classes
- bridge : Separates an object’s interface from its implementation
- composite : A tree structure of simple and composite objects
- decorator : Add responsibilities to objects dynamically
- façade : A single class that represents an entire subsystem
- flyweight : A fine-grained instance used for efficient sharing
- proxy : An object representing another object
behavioral
- interpreter : A way to include language elements in a program
- template method : Encapsulating algorithms to a subclass
- chain of responsibility : A way of passing a request between a chain of objects
- command : Encapsulate method invocation as an object
- iterator : Sequentially access the elements of a collection
- mediator : Centralize complex communication and control between related objects
- memento : Capture and restore an object's internal state
- observer : A way of notifying change to a number of classes
- state : Alter an object's behavior when its state changes
- strategy : Encapsulates an algorithm inside a class
- visitor : Defines a new operation to a class without change
- null object : Provides intelligent "do nothing" behavior, hiding the details
http://www.oodesign.com/design-principles.html
Design Principles: set of guidelines for software development
- Open Close Principle:
o Software entities like classes, modules and functions should be open for
extension but closed for modifications.
- Dependency Inversion Principle:
o High-level modules should not depend on low-level modules.
Both should depend on abstractions.
o Abstractions should not depend on details (concrete classes).
Design should depend on abstractions.
- Principle of Least Knowledge:
o Talk only to your immediate friends.
- Interface Segregation Principle:
o Clients should not be forced to depend upon interfaces that they don't use.
- Single Responsibility Principle
o A class should have only one reason to change.
- Liskov's Substitution Principle
o Derived types must be completely substitutable for their base types.
additional reference sources:
- http://www.vincehuston.org/dp/
- Design Patterns: Elements of Reusable Object-Oriented Software, Nov 1994, Addison-Wesley Professional
- Head First Design Patterns, Oct 2004, O'Reilly Media
DESIGN PATTERNS NOTES }}} */
/* my design patterns comments {{{
----------------------------------------
knowning how to make your own function pointer declaration, assignment and execution
will cover 80% of the design pattern's attempt to implement your project. wrappers
basic data structure know-how covers the other 20%.
design patterns should NOT be thought of as a solution to a problem but as an IDEA
to accomplish the task.
why in "C"? why not. the ideas are what is important here. these are not new ideas.
many of the "design patterns" have been written before any OO languages existed. again,
function pointers, data structure and function routines are all that's needed to run
these programming "tips/tricks/ideas". these will come natural when getting rid of
duplicate code becomes obvious.
the giant list of alternative terminology created to describe the nit-picky difference
(as well as already established terms) for software development is actually quite
detrimental. this leads to "holding hands" during (extreme micro managing or heavily
regulated) software development. again, using patterns as ideas instead of requirements
would help.
redundant terminology notes
---------------------------
supertypes == parent class / a particular base class
interface == abstract supertype
refactoring == complete re-write vs. extend vs. slight modification
instantiate == create, alloc, new (an object) [see factory]
aggregate == group, items
component == an element in the composite (tree)
composite == blind type tree
context == the situation in which the pattern applies
collection == container (array, stack, list, hash, etc.)
invoke == call (a function)
(remote) proxy == remote method invocation
== remote procedure call
== basic network programming
factory == create, alloc, new (the function/method) [see instantiate]
adapter == wrapper for an object('s interface) with a different interface
decorator == wrapper with additional behviors (extend an object)
façade == a function block (for a bunch of stuff to a bunch of objects)
builder == create function (create a bunch of related objects)
visitor == composite façade
proxy == control access (request handler) to an object via:
remote (client/server) vs. virtual (delayed expensive instantiation)
command == to execute() a function pointer
observers == listeners / events / notifications
state == changeable function pointers [see strategy]
strategy == configurable (initialize) function pointers [see state]
template method == class/struct with (abstract/overridable[hooking]) function pointers
flyweight == one instance used to provide many "virtual instances"
chain of responsibility == handlers are objects, and they handle "a" request
a fancy term for a "chain of function handlers"
model view controller (MVC) - an example composite pattern
model == (observer) data, state, logic
view == (composite) presentation, display
controller == (strategy) IO [translates to requests on the model]
model2 == MVC via the web
i.e. server side (controller) dynamic (model) page (view)
my design patterns comments }}} */
#include <stdio.h> // printf
#include <stdlib.h> // malloc free
#include <assert.h> // assert()
#include <string.h> // strcmp()
#include <time.h> // time()
#include <glib.h> // GList GQueue
/* -------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------- */
/* the following structs be used to demonstrate design patterns throughout this file */
/* -------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------- */
typedef struct {
void (*print)(void*); // virtual func set in BaseInit();
char* data;
} BaseStruct;
void BasePrint( void* ptr )
{
if ( ptr )
printf( "\t%s\n", ((BaseStruct*)ptr)->data );
}
void BaseInit( BaseStruct* base )
{
static char* data = "BaseStruct";
if ( base ) {
base->print = BasePrint;
base->data = data;
}
}
BaseStruct* BaseConstructor( void )
{
BaseStruct* base = (BaseStruct*)malloc( sizeof(BaseStruct) );
BaseInit( base );
return base;
}
/* -------------------------------------------------------------------------------- */
// class SubStruct extends BaseStruct
typedef struct {
BaseStruct base;
char* data;
} SubStruct;
void SubPrint( void *ptr )
{
if ( ptr ) {
SubStruct* sub = (SubStruct*)ptr;
BasePrint( &sub->base );
printf( "\t%s\n", sub->data );
}
}
void SubInit( SubStruct* sub )
{
static char* data = "SubStruct";
if ( ! sub )
return;
BaseInit( &sub->base );
sub->base.print = SubPrint; // override virtual function
sub->data = data;
}
SubStruct* SubConstructor( void )
{
SubStruct* sub = (SubStruct*)malloc( sizeof(SubStruct) );
SubInit( sub );
return sub;
}
/* -------------------------------------------------------------------------------- */
void Demo_Extends()
{
SubStruct sub;
printf( "\nStruct Extends\n" );
SubInit( &sub );
sub.base.print( &sub );
}
/* -------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------- */
void a_function(void) { printf( "in a_function()\n" ); }
void b_function(void) { printf( "in b_function()\n" ); }
void c_function(void) { printf( "in c_function()\n" ); }
/* -------------------------------------------------------------------------------- */
typedef struct {
void (*print) (void*); // virtual func set in AbstractInit();
void (*function1)(void); // virtual func set in AbstractInit();
void (*function2)(void); // note: pure virtual
char* data;
} AbstractStruct;
void AbstractPrint( void* ptr )
{
if ( ptr )
printf( "\t%s\n", ((AbstractStruct*)ptr)->data );
}
void AbstractInit( AbstractStruct* abstract, void (*func1) (void) )
{
static char* data = "AbstractStruct";
if ( ! abstract ) {
assert( "abstract: \"this\" is missing\n" );
return;
}
if ( ! func1 ) {
assert( "abstract: missing function assignment\n" );
return;
}
abstract->print = AbstractPrint;
abstract->function1 = a_function;
abstract->function2 = func1;
abstract->data = data;
}
AbstractStruct* AbstractConstructor( void )
{
assert( "am abstract, extend this on your own\n" );
return NULL;
}
/* -------------------------------------------------------------------------------- */
typedef struct {
void (*function1)(void); // note: pure virtual
void (*function2)(void); // note: pure virtual
char* data;
} InterfaceStruct;
void InterfaceInit( InterfaceStruct* iface, void (*func1) (void), void (*func2) (void), char* data )
{
if ( ! iface ) {
assert( "interface: \"this\" is missing\n" );
return;
}
if ( ! func1 || ! func2 ) {
assert( "interface: missing function assignment\n" );
return;
}
iface->function1 = func1;
iface->function2 = func2;
iface->data = data;
}
InterfaceStruct* InterfaceConstructor( void )
{
assert( "am interface, impliment this on your own\n" );
return NULL;
}
/* -------------------------------------------------------------------------------- */
// class ConcreteStruct extends AbstractStruct implements InterfaceStruct
typedef struct {
AbstractStruct abstract;
InterfaceStruct interface;
} ConcreteStruct;
void ConcretePrint( void* ptr )
{
if ( ptr ) {
ConcreteStruct* c = (ConcreteStruct*)ptr;
AbstractPrint( &c->abstract );
printf( "\t%s\n", c->interface.data );
}
}
void ConcreteInit( ConcreteStruct* c )
{
static char* data = "ConcreteStruct";
if ( !c )
return;
AbstractInit( &c->abstract, a_function );
InterfaceInit( &c->interface, b_function, c_function, data );
c->abstract.print = ConcretePrint; // override virtual function
}
ConcreteStruct* ConcreteConstructor( void )
{
ConcreteStruct* c = (ConcreteStruct*)malloc( sizeof(ConcreteStruct) );
ConcreteInit( c );
return c;
}
/* -------------------------------------------------------------------------------- */
void Demo_Abstract_Implements()
{
ConcreteStruct c;
printf( "\nStruct Extends and Implements\n" );
ConcreteInit( &c );
c.abstract.print( &c );
}
/* -------------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------------- */
/* Creational Design Patterns {{{
* ======================================== */
/* Factory (Simplified version of Factory Method): {{{2
* ----------------------------------------
* - Creates objects without exposing the instantiation logic to the client.
* - Refers to the newly created object through a common interface.
*/
/* THE DEMO */
void Factory_Simple()
{
BaseStruct* base;
SubStruct* sub;
ConcreteStruct* crete;
printf( "\nFactory_Simple()\n" );
base = BaseConstructor();
sub = SubConstructor();
crete = ConcreteConstructor();
if ( base ) {
printf( "\t%s\n", base->data );
free( base ); base = NULL; /* clean up */
}
if ( sub ) {
printf( "\t%s %s\n", sub->base.data, sub->data );
free( sub ); sub = NULL; /* clean up */
}
if ( crete ) {
printf( "\t%s %s\n", crete->abstract.data, crete->interface.data );
free( crete ); crete = NULL; /* clean up */
}
}
/* Factory (Simplified version of Factory Method): }}}2 */
/* Abstract Factory: {{{2
* ----------------------------------------
* - Offers the interface for creating a family of related objects, or
* dependent objects without explicitly specifying their concrete classes.
* - A hierarchy that encapsulates: many possible "platforms", and the
* construction of a suite of "products".
* - The [new] operator considered harmful.
*/
// class AF1Struct extends BaseStruct
typedef struct {
BaseStruct base;
char* data;
} AF1Struct;
void AF1_Print( void* ptr )
{
if ( ptr )
printf( "\t%s\n", ((AF1Struct*)ptr)->data );
}
AF1Struct* AF1Constructor( void )
{
static char* data = "AF1Struct";
AF1Struct* af1 = (AF1Struct*)malloc( sizeof(AF1Struct) );
if ( af1 ) {
BaseInit( &af1->base );
af1->base.print = AF1_Print; // override virtual function
af1->data = data;
}
return af1;
}
// class AF2Struct extends BaseStruct
typedef struct {
BaseStruct base;
char* data;
int moredata;
} AF2Struct;
void AF2_Print( void* ptr )
{
if ( ptr ) {
AF2Struct* af2 = (AF2Struct*)ptr;
printf( "\t%s : %d\n", af2->data, af2->moredata );
}
}
AF2Struct* AF2Constructor( void )
{
static char* data = "AF2Struct";
AF2Struct* af2 = (AF2Struct*)malloc( sizeof(AF2Struct) );
if ( af2 ) {
BaseInit( &af2->base );
af2->base.print = AF2_Print; // override virtual function
af2->data = data;
af2->moredata = 1234;
}
return af2;
}
/* THE DEMO */
void Abstract_Factory()
{
int i;
BaseStruct* base[2];
printf( "\nAbstract_Factory()\n" );
base[0] = (BaseStruct*)AF1Constructor();
base[1] = (BaseStruct*)AF2Constructor();
for ( i = 0; i < 2; i++ ) {
if ( base[i] ) {
base[i]->print( base[i] );
free( base[i] ); base[i] = NULL; /* clean up */
} }
}
/* Abstract Factory: }}}2 */
/* Factory Method: {{{2
* ----------------------------------------
* - Defines an interface for creating objects,
* but let subclasses decide which class to instantiate.
* i.e Lets a class defer instantiation to subclasses.
* - Refers to the newly created object through a common interface.
*
* - Defining a "virtual" constructor.
* - The [new] operator considered harmful.
*/
BaseStruct* FM_VirtualConstructor( int type )
{
switch( type ) {
case 0:
return (BaseStruct*)AF1Constructor();
case 1:
return (BaseStruct*)AF2Constructor();
default:
break;
}
return NULL;
}
/* THE DEMO */
void Factory_Method()
{
int i;
BaseStruct* base[2];
printf( "\nFactory_Method()\n" );
for ( i = 0; i < 2; i++ )
base[i] = FM_VirtualConstructor(i);
for ( i = 0; i < 2; i++ ) {
if ( base[i] ) {
base[i]->print( base[i] );
free( base[i] ); base[i] = NULL; /* clean up */
} }
}
/* Factory Method: }}}2 */
/* Builder: {{{2
* ----------------------------------------
* - Defines an instance for creating an object
* but letting subclasses decide which class to instantiate
* - Allows a finer control over the construction process.
*
* - Separate the construction of a complex object from its representation
* so that the same construction process can create different representations.
* - Parse a complex representation, create one of several targets.
*/
/* builder == create function (create a bunch of related objects) */
BaseStruct** Builder_Parser( int* types, int count )
{
BaseStruct** bases;
if ( count <= 0 )
return NULL;
bases = (BaseStruct**)malloc( sizeof(BaseStruct*) * count );
if ( bases ) {
int i;
for ( i = 0; i < count; i++ ) {
switch( types[i] ) {
case 0:
bases[i] = (BaseStruct*)AF1Constructor();
break;
case 1:
bases[i] = (BaseStruct*)AF2Constructor();
break;
default:
bases[i] = NULL;
break;
} } }
return bases;
}
/* THE DEMO */
void Builder()
{
int complex_representation[] = { 0, 1, 0, 0, 1, 1, 0, 1 /*etc*/ };
int count = sizeof( complex_representation ) / sizeof( complex_representation[0] );
int i;
BaseStruct** bases;
printf( "\nBuilder()\n" );
bases = Builder_Parser( complex_representation, count );
if ( ! bases )
return;
for ( i = 0; i < count; i++ ) {
if ( bases[i] ) {
bases[i]->print( bases[i] );
free( bases[i] ); bases[i] = NULL; /* clean up */
} }
free( bases ); /* clean up */
}
/* Builder: }}}2 */
/* Prototype: {{{2
* ----------------------------------------
* - Specify the kinds of objects to create using a prototypical instance,
* and create new objects by copying this prototype.
* - Co-opt one instance of a class for use as a breeder of all future instances.
* - The [new] operator considered harmful.
*/
typedef struct ProtoAbstractStruct {
struct ProtoAbstractStruct* (*clone)(void); // note: pure virtual
BaseStruct base;
} ProtoAbstractStruct;
void ProtoAbstractInit( ProtoAbstractStruct* proto, struct ProtoAbstractStruct* (*clone)(void) )
{
static char* data = "ProtoAbstractStruct";
if ( ! proto ) {
assert( "proto abstract: \"this\" is missing\n" );
return;
}
if ( ! clone ) {
assert( "proto abstract: missing clone function\n" );
return;
}
BaseInit( &proto->base );
proto->base.data = data;
}
ProtoAbstractStruct* ProtoAbstractConstructor( void )
{
assert( "am proto abstract, extend this on your own\n" );
return NULL;
}
// class Proto1Struct extends ProtoAbstractStruct
typedef struct {
ProtoAbstractStruct proto;
char* data;
} Proto1Struct;
void Proto1_Print( void* ptr )
{
if ( ptr ) {
Proto1Struct* proto1 = (Proto1Struct*)ptr;
BasePrint( &proto1->proto.base );
printf( "\t%s\n", proto1->data );
}
}
ProtoAbstractStruct* Proto1Constructor( void )
{
static char* data = "Proto1Struct";
Proto1Struct* proto1 = (Proto1Struct*)malloc( sizeof(Proto1Struct) );
if ( proto1 ) {
BaseInit( &proto1->proto.base );
proto1->proto.base.print = Proto1_Print; // override virtual function
proto1->proto.clone = Proto1Constructor;
proto1->data = data;
}
return (ProtoAbstractStruct*)proto1;
}
// class Proto2Struct extends ProtoAbstractStruct
typedef struct {
ProtoAbstractStruct proto;
char* data;
int moredata;
} Proto2Struct;
void Proto2_Print( void* ptr )
{
if ( ptr ) {
Proto2Struct* proto2 = (Proto2Struct*)ptr;
BasePrint( &proto2->proto.base );
printf( "\t%s : %d\n", proto2->data, proto2->moredata );
}
}
ProtoAbstractStruct* Proto2Constructor( void )
{
static char* data = "Proto2Struct";
Proto2Struct* proto2 = (Proto2Struct*)malloc( sizeof(Proto2Struct) );
if ( proto2 ) {
BaseInit( &proto2->proto.base );
proto2->proto.base.print = Proto2_Print; // override virtual function
proto2->proto.clone = Proto2Constructor;
proto2->data = data;
}
return (ProtoAbstractStruct*)proto2;
}
/* THE DEMO */
void Prototype()
{
int i, j;
ProtoAbstractStruct* protos[8];
printf( "\nPrototype()\n" );
protos[0] = (ProtoAbstractStruct*)Proto1Constructor();
protos[1] = (ProtoAbstractStruct*)Proto2Constructor();
for ( i = 2; i < 8; i++ ) {
j = i & 0x1;
if ( protos[j] )
protos[i] = (ProtoAbstractStruct*)protos[j]->clone();
}
/* show the results */
for ( i = 0; i < 8; i++ ) {
if ( protos[i] ) {
protos[i]->base.print( protos[i] ); printf( "\n" );
free( protos[i] ); protos[i] = NULL; /* clean up */
} }
}
/* Prototype: }}}2 */
/* Singleton: {{{2
* ----------------------------------------
* - Ensure that only one instance of a class is created.
* - Provide a global access point to the object.
*
* - Encapsulated "just-in-time initialization" or "initialization on first use".
*/
// the following indirection is needed to help make the singleton pattern design work in C:
//
// here's why, the following will break in C
//
// struct XYZ { /* struct member (not pointer) */
// __TheRealSingletonObject data;
// ...
// }
//
// { /* stack allocation */
// __TheRealSingletonObject element;
// ...
// }
//
// /* dynamically allocated */
// __TheRealSingletonObject* item = (__TheRealSingletonObject*)malloc( sizeof(__TheRealSingletonObject) );
//
// [data], [element] and [item] all do not refer to same singleton object...
#define __TheRealSingletonObject BaseStruct
// the indirection...
typedef struct {
__TheRealSingletonObject* the_real_singleton;
} SingletonStruct;
SingletonStruct* _singleton = NULL;
#define Singleton_GetInstance SingletonConstructor
SingletonStruct* SingletonConstructor()
{
if ( ! _singleton ) {
_singleton = (SingletonStruct*)malloc( sizeof(SingletonStruct) );
if ( _singleton )
_singleton->the_real_singleton = BaseConstructor();
}
return _singleton;
}
void SingletonInit( SingletonStruct* singleton )
{
if ( singleton ) {
SingletonStruct* s = Singleton_GetInstance();
if ( s )
singleton->the_real_singleton = s->the_real_singleton;
}
}
/* THE DEMO */
void Singleton()
{
struct SingletonTest {
SingletonStruct struct_singleton_object;
} test;
int i;
SingletonStruct* singleton[6];
SingletonStruct local_singleton_object;
SingletonStruct* dynamic_singleton;
printf( "\nSingleton()\n" );
/* these are all the same */
singleton[0] = SingletonConstructor();
singleton[1] = Singleton_GetInstance();
singleton[2] = _singleton;
/* trick C */
/* these are all essentially the same */
SingletonInit( &test.struct_singleton_object );
singleton[3] = &test.struct_singleton_object;
SingletonInit( &local_singleton_object );
singleton[4] = &local_singleton_object;
dynamic_singleton = (SingletonStruct*)malloc( sizeof(SingletonStruct) );
SingletonInit( dynamic_singleton );
singleton[5] = dynamic_singleton;
for ( i = 0; i < 6; i++ )
if ( singleton[i] )
printf( "\t[%d] pointer:%p singleton:%p\n", i, singleton[i], singleton[i]->the_real_singleton );
/* clean up */
if ( dynamic_singleton )
free ( dynamic_singleton );
// DO NOT DESTROY THE SINGLETON HERE (unless planned)...
}
/* Singleton: }}}2 */
/* Object Pool: {{{2
* ----------------------------------------
* - Reuses and shares objects that are expensive to create.
*/
#define OBJECT_POOL_LIMIT 3
#define ObjectPoolConstructor ObjectPool_GetInstance
#define ObjectPoolFree(x) x->alive = 0
//#define objpool_dbg_printf printf
#define objpool_dbg_printf(...)
typedef struct {
BaseStruct base;
int alive;
} ObjectPoolStruct;
ObjectPoolStruct* _object_pool[OBJECT_POOL_LIMIT] = { NULL, NULL, NULL };
ObjectPoolStruct* ObjectPool_GetInstance()
{
static char* data[3] = { "pool0", "pool1", "pool2" };
int i;
// logic order:
// 1 allocated & not alive
// 2 newly allocated
// 3 none to return
// rule 1
for ( i = 0; i < OBJECT_POOL_LIMIT; i++ ) {
if ( _object_pool[i] && ! _object_pool[i]->alive ) {
objpool_dbg_printf( "*** get: reusing %d\n", i );
_object_pool[i]->alive = 1;
return _object_pool[i];
} }
// rule 2
for ( i = 0; i < OBJECT_POOL_LIMIT; i++ ) {
ObjectPoolStruct* obj;
if ( _object_pool[i] ) continue;
obj = (ObjectPoolStruct*)malloc( sizeof(ObjectPoolStruct) );
if ( ! obj )
return NULL;
objpool_dbg_printf( "*** get: allocating %d\n", i );
_object_pool[i] = obj;
BaseInit( &obj->base );
obj->base.data = data[i];
obj->alive = 1;
return obj;
}
objpool_dbg_printf( "*** get: none\n" );
// rule 3
return NULL;
}
/* THE DEMO */
void Object_Pool()
{
ObjectPoolStruct* objs[OBJECT_POOL_LIMIT] = { NULL, NULL, NULL };
int i, j;
printf( "\nObject_Pool()\n" );
srand( time(NULL) );
for ( i = 0; i < 8; i++ ) {
j = rand() % OBJECT_POOL_LIMIT;
if ( objs[j] ) {
objpool_dbg_printf( "*** run: pre nuke %d\n", j );
ObjectPoolFree( objs[j] );
objs[j] = NULL;
}
objs[j] = ObjectPool_GetInstance();
if ( objs[j] ) {
objpool_dbg_printf( "*** run: getting %d\n", j );
objs[j]->base.print( &objs[j]->base );
}
j = rand() % OBJECT_POOL_LIMIT;
if ( objs[j] ) {
objpool_dbg_printf( "*** run: post nuke %d\n", j );
ObjectPoolFree( objs[j] );
objs[j] = NULL;
} }
printf( "\t*** final results ***\n" );
for ( i = 0; i < OBJECT_POOL_LIMIT; i++ ) {
if ( objs[i] && objs[i]->alive )
objs[i]->base.print( &objs[i]->base );
}
printf( "\t---\n" );
for ( i = 0; i < OBJECT_POOL_LIMIT; i++ ) {
if ( _object_pool[i] )
_object_pool[i]->base.print( &_object_pool[i]->base );
}
}
/* Object Pool: }}}2
* Creational Design Patterns }}}
* Structural Design Patterns {{{
* ======================================== */
/* Adapter: {{{2
* ----------------------------------------
* - Convert the interface of a class into another interface clients expect.
* i.e. Lets classes work together, that could not otherwise because of
* incompatible interfaces.
*
* - Wrap an existing class with a new interface.
* - Impedance match an old component to a new system
*/
typedef struct {
int data;
void (*print)(int); // set in LegacyInit();
} LegacyStruct;
void Legacy_Print( int data )
{
printf( "\t%d\n", data );
}
void LegacyInit( LegacyStruct* legacy )
{
if ( ! legacy )
return;
legacy->print = Legacy_Print;
legacy->data = 5678;
}
typedef struct {
BaseStruct base;