简单工厂不符合开闭原则,所以这里不把创建每个对象放在一个工厂里,而是把创建工厂抽象出来,每次创建一个具体对象由每个对象工厂自己常见,符合开闭原则。
1 #include<iostream> 2 using namespace std; 3 #include<string> 4 5 //简单工厂不符合开闭原则,所以这里不把创建每个水果对象放在一个工厂里,而是把创建工厂抽象出来,每次创建一个具体水果由每个对象工厂自己常见,达到开闭原则。 6 7 //抽象水果 8 class abstractFruit{ 9 public: 10 virtual void showName()=0; 11 }; 12 //苹果 13 class apple:public abstractFruit{ 14 public: 15 virtual void showName() 16 { 17 cout<<"apple"<<endl; 18 } 19 }; 20 //梨 21 class pear:public abstractFruit{ 22 public: 23 virtual void showName() 24 { 25 cout<<"pear"<<endl; 26 } 27 }; 28 //香蕉 29 class banana:public abstractFruit{ 30 public: 31 virtual void showName() 32 { 33 cout<<"banana"<<endl; 34 } 35 }; 36 37 //抽象水果工厂 38 class abstractFactory{ 39 public: 40 virtual abstractFruit* createFruit()=0; 41 }; 42 43 //苹果工厂 44 class appleFactory:public abstractFactory{ 45 public: 46 virtual abstractFruit* createFruit(){ 47 return new apple; 48 } 49 }; 50 51 //梨工厂 52 class pearFactory:public abstractFactory{ 53 public: 54 virtual abstractFruit* createFruit(){ 55 return new pear; 56 } 57 }; 58 59 //香蕉工厂 60 class bananaFactory:public abstractFactory{ 61 public: 62 virtual abstractFruit* createFruit(){ 63 return new banana; 64 } 65 }; 66 67 68 int main() 69 { 70 //创建一个抽象工厂 71 abstractFactory *factory=NULL; 72 //创建一个抽象水果 73 abstractFruit* fruit=NULL; 74 75 76 //创建一个苹果 77 factory=new appleFactory; 78 fruit=factory->createFruit(); 79 fruit->showName(); 80 delete factory; 81 delete fruit; 82 83 //创建一个香蕉 84 factory=new bananaFactory; 85 fruit=factory->createFruit(); 86 fruit->showName(); 87 delete factory; 88 delete fruit; 89 90 //创建一个梨 91 factory=new pearFactory; 92 fruit=factory->createFruit(); 93 fruit->showName(); 94 delete factory; 95 delete fruit; 96 97 return 0; 98 }
来源:https://www.cnblogs.com/njit-sam/p/12652836.html