1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 7 class STAbstractProductA 8 { 9 public: 10 virtual void use() = 0; 11 }; 12 13 class STProductA1: public STAbstractProductA 14 { 15 public: 16 virtual void use() 17 { 18 cout<< "use ProductA1............"<< endl; 19 } 20 }; 21 22 class STProductA2: public STAbstractProductA 23 { 24 public: 25 virtual void use() 26 { 27 cout<< "use ProductA2............"<< endl; 28 } 29 }; 30 31 class STAbstractProductB 32 { 33 public: 34 virtual void eat() = 0; 35 }; 36 37 class STProductB1: public STAbstractProductB 38 { 39 public: 40 virtual void eat() 41 { 42 cout<< "eat ProductB1............"<< endl; 43 } 44 }; 45 46 class STProductB2: public STAbstractProductB 47 { 48 public: 49 virtual void eat() 50 { 51 cout<< "eat ProductB2............"<< endl; 52 } 53 }; 54 55 class STAbstractFactory 56 { 57 public: 58 virtual STAbstractProductA* CreateProductA() = 0; 59 virtual STAbstractProductB* CreateProductB() = 0; 60 }; 61 62 class STConcreteFactoryA: public STAbstractFactory 63 { 64 public: 65 virtual STAbstractProductA* CreateProductA() 66 { 67 return new STProductA1; 68 } 69 virtual STAbstractProductB* CreateProductB() 70 { 71 return new STProductB1; 72 } 73 }; 74 75 class STConcreteFactoryB: public STAbstractFactory 76 { 77 public: 78 virtual STAbstractProductA* CreateProductA() 79 { 80 return new STProductA2; 81 } 82 virtual STAbstractProductB* CreateProductB() 83 { 84 return new STProductB2; 85 } 86 }; 87 88 int main(int argc, char* argv[]) 89 { 90 STAbstractFactory* fc = new STConcreteFactoryA(); 91 STAbstractProductA* pa = fc->CreateProductA(); 92 STAbstractProductB* pb = fc->CreateProductB(); 93 94 pa->use(); 95 pb->eat(); 96 97 STAbstractFactory* fc2 = new STConcreteFactoryB(); 98 STAbstractProductA* pa2 = fc2->CreateProductA(); 99 STAbstractProductB* pb2 = fc2->CreateProductB(); 100 101 pa2->use(); 102 pb2->eat(); 103 104 return 0; 105 } 106 //////////////////////////////////////// 107 [[email protected] ~/learn_code/design_pattern/9_abstract_factory]$ ./abstract_factory 108 use ProductA1............ 109 eat ProductB1............ 110 use ProductA2............ 111 eat ProductB2............
时间: 2024-12-09 02:34:29