工厂方法模式是对简单工厂模式的改进
情景:
对于简单工厂模式,如果工厂需要生产CPUC类,则必须修改工厂类produceCPU(string name)方法,增加类似的判断:
if (name == "CPUC") ret = new CPUC()
显然违背了开放封闭原则(对扩展开放,对修改关闭)
所谓工厂方法模式,就是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法模式使一个类的实例化延迟到其子类,一个工厂只对应一个一类的实例化
代码:
#include <iostream> using namespace std; class CPU { public: virtual void show() = 0; virtual ~CPU(){} // 抽象基类的析构函数必须是虚析构,以保证delete基类指针的时候,子类的析构函数能被调用,实现内存的完全清理 }; class CPUA : public CPU { public: virtual void show() { cout << "I am CPUA" << endl; } ~CPUA() { cout << "CPUA 被析构" << endl; } }; class CPUB : public CPU { public: virtual void show() { cout << "I am CPUB" << endl; } ~CPUB() { cout << "CPUB被析构" << endl; } }; class Factory { public: virtual CPU * produceCPU() = 0; virtual ~Factory() {} }; class FactoryA : public Factory { public: virtual CPU *produceCPU() { return new CPUA(); } ~FactoryA() { cout << "FactoryA被析构" << endl; } }; class FactoryB : public Factory { public: virtual CPU *produceCPU() { return new CPUB(); } ~FactoryB() { cout << "FactoryB被析构" << endl; } }; void test() { Factory *f = new FactoryA(); CPU *cpu = f->produceCPU(); cpu->show(); delete cpu; delete f; f = new FactoryB(); cpu = f->produceCPU(); cpu->show(); delete cpu; delete f; cpu = NULL; f = NULL; } int main() { test(); cin.get(); return 0; }
现在要生产CPU类,只要创建一个FactoryC类,继承Factory,实现produceCPU()方法,即可:
class CPUC : public CPU { public: virtual void show() { cout << "I am CPUC" << endl; } ~CPUC() { cout << "CPUC被析构" << endl; } }; class FactoryC : public Factory { public: CPU *produceCPU() { return new CPUC(); } ~FactoryC() { cout << "FactoryC 被析构" << endl; } }; void test2() { Factory *f = new FactoryC(); CPU *cpu = f->produceCPU(); cpu->show(); delete cpu; delete f; }
效果: