Factory mode is primarily used to encapsulate object creation in 3 categories: Simple Factory, Factory method (factory), abstract factory.
The simple plant consists of 3 constituent elements: Abstract products, specific products, specific factories ( simple plants ), with the following structural drawings:
C + + implementation:
//Abstract ProductsclassCar { Public: Virtual stringGetDescription () =0;};//Specific ProductsclassAudi: PublicCar {stringGetDescription () {return "Audi"; }};classBMW: PublicCar {stringGetDescription () {return "BMW"; }};classFord: PublicCar {stringGetDescription () {return "Ford"; }};classHummer: PublicCar {stringGetDescription () {return "Hummer"; }};classToyota: PublicCar {stringGetDescription () {return "Toyota"; }};classBentley: PublicCar {stringGetDescription () {return "Bentley"; }};//Simple FactoryclassCarfactory { Public: Staticcar* Createcar (stringname) { if(Name = ="Audi") return NewAudi; Else if(Name = ="BMW") return NewBMW; Else if(Name = ="Ford") return NewFord; Else if(Name = ="Hummer") return NewHummer; Else if(Name = ="Toyota") return NewToyota; Else if(Name = ="Bentley") return NewBentley; }};intMain () {Car*mycar = Carfactory::createcar ("Audi"); cout<< mycar->getdescription () <<Endl; Mycar= Carfactory::createcar ("BMW"); cout<< mycar->getdescription () <<Endl; DeleteMycar;}
As can be seen in the simple factory model, a specific factory is responsible for the creation of all specific products, suitable for the case of a small product category. When new products are added, we need to modify the implementation logic of the simple factory and violate the open closure principle.
The factory method model adds an abstract factory based on the simple factory model.
Abstract factories define only the interfaces that create objects, and the specific subclasses are responsible for the creation of specific objects.
C + + implementation:
//Abstract FactoryclassCarfactory { Public: Virtualcar* Createcar () =0;};//Specific FactoryclassAuticarfactory: PublicCarfactory { Public: Car* Createcar () {return NewAudi;}};classBmwcarfactory: PublicCarfactory { Public: Car* Createcar () {return NewBMW;}};intMain () {carfactory*PCF =Newauticarfactory; Car*c = pcf->Createcar (); cout<< c->getdescription () <<Endl; DeletePCF; PCF=Newbmwcarfactory; C= pcf->Createcar (); cout<< c->getdescription () <<Endl; DeletePCF;}
In factory method mode, when a new product category is added, it is only necessary to create a product class and a new corresponding factory class, without destroying the original code and following the open closure principle.
Factory mode (Factory pattern)