情景:
随着业务的扩大,原来的工厂除了生产cpu,也开始生产硬盘了。如果继续使用简单工厂模式、工厂方法模式,就有些鞭长莫及了。此时就轮到抽象工厂模式登场了。
定义:为提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类(将类的实例化推迟到了子类实现)
工厂方法和抽象工厂的比较:
工厂方法模式:一个工厂只定义一个接口,负责生产一类产品
抽向工厂模式: 一个工厂定义多个相关接口,每一个接口对应生产一类产品
#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 HardDisk { public: virtual void show() = 0; virtual ~HardDisk() {} }; class HardDiskA : public HardDisk { public: virtual void show() { cout << "I am HardDiskA" << endl;; } ~HardDiskA() { cout << "HardDiskA 被析构" << endl; } }; class HardDiskB : public HardDisk { public: virtual void show() { cout << "I am HardDiskB" << endl; } ~HardDiskB() { cout << "HardDiskB 被析构" << endl; } }; class Factory { public: virtual CPU * produceCPU() = 0; virtual HardDisk *produceHardDisk() = 0; virtual ~Factory() {} }; class FactoryA : public Factory { public: virtual CPU *produceCPU() { return new CPUA(); } virtual HardDisk *produceHardDisk() { return new HardDiskA(); } ~FactoryA() { cout << "FactoryA被析构" << endl; } }; class FactoryB : public Factory { public: virtual CPU *produceCPU() { return new CPUB(); } virtual HardDisk *produceHardDisk() { return new HardDiskB(); } ~FactoryB() { cout << "FactoryB被析构" << endl; } }; void test() { Factory *f = NULL; CPU *cpu = NULL; HardDisk *disk = NULL; f = new FactoryA(); cpu = f->produceCPU(); cpu->show(); disk = f->produceHardDisk(); disk->show(); delete cpu; delete disk; delete f; f = new FactoryB(); cpu = f->produceCPU(); cpu->show(); disk = f->produceHardDisk(); disk->show(); delete cpu; delete disk; delete f; } int main() { test(); cin.get(); return 0; }
效果: