Factory mothed pattern, called factory method mode
First, let's take a look at how gof defines the factory method mode:
"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer Instantiation to subclasses."-gof
"Define an interface to create an object and let the subclass decide which class to instantiate. The factory method mode delays the class Instantiation to the subclass"-gof
Abstract Factory(Abstractfactory):Is the core of the factory method model. The specific factory must implement the abstract method defined in the abstract factory.
Specific Factory(Concretefactory):Implement all the abstract methods defined in the abstract factory, including the logic closely related to the business.
Abstract Product(Abstractproduct):Super category of all specific products, that is, the common parent category of specific products.
Specific products(Concreteproduct):This role implements the interface defined by the abstract Product role.
In C ++, the C ++ polymorphism is actually used. Instance: A factory produces Mercedes-Benz cars, a factory generates Audi cars, and tests are required.
1 Class Car 2 { 3 Public : 4 Virtual Void Run () = 0 ; 5 }; 6 7 Class Audicar: Public Car 8 { 9 Public : 10 Void Run (); 11 }; 12 Void Audicar: Run () 13 { 14 STD: cout < " Audi is running " < STD: Endl; 15 } 16 17 Class Benzcar: Public Car 18 { 19 Public : 20 Void Run (); 21 } 22 Void Benzcar: Run () 23 { 24 STD: cout < " Benz is running " < STD: Endl; 25 }; 26 27 Class Carfactory 28 { 29 Public : 30 Virtual Car * createcar () = 0 ; 31 }; 32 33 Class Audicarfactory: Public Carfactory 34 { 35 Public : 36 Car * Createcar (); 37 }; 38 Car * Audicarfactory: createcar () 39 { 40 Return New Audicar (); 41 } 42 43 Class Benzcarfactory: Public Carfactory 44 { 45 Public : 46 Car * Createcar (); 47 }; 48 Car * Benzcarfactory: createcar () 49 { 50 Return New Benzcar (); 51 } 52 53 Void Createandtest (carfactory * P) 54 { 55 Car * c = p-> Createcar (); 56 C-> Run (); 57 Delete C; 58 } 59 60 Int Main ( Int Argc, Char * Argv) 61 { 62 Carfactory * P1 = New Benzcarfactory (); // The subclass determines the object to be instantiated. 63 Carfactory * P2 = New Audicarfactory (); 64 Createandtest (P1 ); 65 Createandtest (P2 ); 66 Delete P1; 67 Delete P2; 68 Return 0 ; 69 }
Running result: