1. Simple Factory mode
Characteristics: Need to make judgments in the factory class, so as to create the corresponding products
enumetype{MASTER, solider};//Mage, Warrior//virtual base classclassrole{ Public: Virtual voidShow () =0; Virtual voidInit () =0;};classMaster: Publiccrole{ Public: voidShow () {Std::cout<<"This is a master"<<Std::endl; } voidInit () {...}};classSolider: Publiccrole{ Public: voidShow () {Std::cout<<"This is a solider"<<Std::endl; } voidInit () {...}};classfactory{ Public: Crole*Create (ETYPE type) {Crole* PRole =NULL; Switch(Type): { CaseMaster:prole=NewMaster; Break; CaseSolider:prole=Newsolider; Break; } } if(pRole) {pRole-Init (); } returnpRole;};
Disadvantages:
Each new class needs to change the branch of the Factory factory class.
UML diagram for simple Factory mode:
2. Factory mode
Feature: Define an interface for creating objects, and then let subclasses decide which class to instantiate. Defers the instantiation of a class to its subclasses.
classfactory{ Public: VirtualCrole * Create () =0; };classMasterfactory: Publicfactory{ Public: Master*Create () {return NewMaster; }};classSoliderfactory: Publicfactory{ Public: Solider*Create () {return Newsolider; }};
Disadvantages:
For each additional product, you need to create a new factory.
In a relatively simple factory model, the factory model needs to define more factory classes, and the simple factory model requires only one factory, which is then partitioned in the factory according to the switch.
UML diagram of the factory method:
3. Abstract Factory mode
Features: Provides an interface to create a series of related or interdependent objects without specifying their specific classes.
A factory that provides a product of a certain type.
classsingle{ Public: Virtual voidShow () =0;}; classSinglea: Publicsingle{ Public: voidShow () {Std::cout<<"Singlea"<<Std::endl; }};classSingleb: Publicsingle{voidShow () {Std::cout<<"Singleb"<<Std::endl; }}; ////classmultiple{ Public: Virtual voidShow () =0;};classMultiplea: Publicmultiple{ Public: voidShow () {Std::cout<<"Multiplea"<<Std::endl; }};classMultipleb: Publicmultiple{voidShow () {Std::cout<<"Multipleb"<<Std::endl; }};classfactory{ Public: VirtualSingle * Createsingle () =0; VirtualMultiple * createmultiple () =0;};//Factorya specifically to produce a model a .classFactorya: Publicfactory{ Public: Single*Createsingle () {return NewSinglea (); } Multiple*createmultiple () {return NewMultiplea (); }};//Factoryb specializes in producing B-models.classFactoryb: Publicfactory{ Public: Single*Createsingle () {return NewSingleb (); } Multiple*createmultiple () {return NewMultipleb (); }};
UML diagram for abstract Factory mode:
C + + Factory mode