Original address:
Http://www.cnblogs.com/hebaichuanyeah/p/5459869.html
A factory pattern is defined as a class (factory) that creates an object, which is used to instantiate a specified subclass.
1. Simple Factory mode
example, if there is a code class, Java,c#,c 艹, and so on is the subclass of the class, by Codefactory to instantiate subclasses. and rewrite the virtual function print in the subclass.
Note: In C 艹, if a child class's resource is freed with a pointer from the parent class, and the destructor in the parent class is not a virtual function, then the destructor of the subclass is not called, and the resource of the subclass is not freed, resulting in a memory leak.
#include"iostream"using namespacestd;classcode{ Public: Code () {}; Virtual voidPrintstringstr) =0; Virtual~Code () {};};classCSharp: Publiccode{ Public: CSharp () {}voidPrintstringstr) {cout<<"Console.WriteLine (\ ""<<str<<"\");"<<Endl; }};classCfuck: Publiccode{ Public: Cfuck () {}voidPrintstringstr) {cout<<"cout<< (\ ""<<str<<"\");"<<Endl; } };classCProgram: Publiccode{ Public: CProgram () {}voidPrintstringstr) {cout<<"printf (\ ""<<str<<"\");"<<Endl; }};classJava: Publiccode{ Public: Java () {}voidPrintstringstr) {cout<<"System.out.printf (\ ""<<str<<"\");"<<Endl; }};classcodefactory{ Public: Code* Createwhatcode (stringname) { if(Name = ="CSharp") return NewCSharp (); if(Name = ="Java") return NewJava (); if(Name = ="CProgram") return NewCProgram (); if(Name = ="Cfuck") return NewCfuck (); }};main () {Codefactory factory; stringprogramname[4]={"CSharp","CProgram","Cfuck","Java"}; for(intI=0;i<4; i++) {Code* Code =Factory.createwhatcode (Programname[i]); Code->print ("Hello World"); DeleteCode; }}
Run results
C + + and Factory mode