工厂方法(Factory Method)模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
#include <iostream> using namespace std; class Fruit{ public: virtual void show()=0; }; class Apple:public Fruit{ public: void show(){ cout<<"i am an apple"<<endl; } }; class Pear:public Fruit{ public: void show(){ cout<<"i am a pear"<<endl; } }; class FruitFactory{ public: virtual Fruit * createFruit()=0; }; class AppleFactory:public FruitFactory{ public: Fruit * createFruit(){ return new Apple(); } }; class PearFactory:public FruitFactory{ public: Fruit * createFruit(){ return new Pear(); } }; int main(int argc, char* argv[]) { //工厂方法模式 //创建不同的工厂,各自负责各自的产品 FruitFactory * applefactory = new AppleFactory(); Fruit * product = applefactory->createFruit(); product->show(); delete product; delete applefactory; FruitFactory * pearfactory = new PearFactory(); Fruit * product2 = pearfactory->createFruit(); product2->show(); delete product2; delete applefactory; return 0; }
优点就是可以分开创建新工厂类,新产品类,不必像简单工厂模式一样在原来的代码上进行修改,可扩展性大大提高。
时间: 2024-10-21 09:53:41