含义:抽象工厂将“抽象零件”组装成“抽象产品”
理解:相比于工厂方法模式,可以根据不同的接口创建不同的产品,说白了就是将一个接口变成两个接口,各自返回不同的抽象产品
例子:
class Car //抽象产品 { public: virtual void name() = 0; }; class BenciCar: public Car { public: void name() { cout << "BenCi Car" << endl; } }; class BaomaCar: public Car { public: void name() { cout << "Baoma Car" << endl; } };
class Bus //抽象产品 { public: virtual void name() = 0; }; class BenciBus: public Bus { public: void name() { cout << "Benci Bus" << endl; } }; class BaomaBus: public Bus { public: void name() { cout << "Baoma Bus" << endl; } };
class Factory //抽象工厂 { public: virtual Car* createCar() = 0; //隐藏具体的复杂的对象创建过程 virtual Bus* createBus() = 0; //隐藏具体的复杂的对象创建过程 }; class BenciFactory: public Factory { public: Car* createCar() { return new BenciCar; } Bus* createBus() { return new BenciBus; } }; class BaomaFactory: public Factory { public: Car* createCar() { return new BaomaCar; } Bus* createBus() { return new BaomaBus; } };
int main() { Factory* bmf = new BaomaFactory(); Car* bmc = bmf->createCar(); Bus* bmb = bmf->createBus(); bmc->name(); bmb->name(); Factory* bcf = new BenciFactory(); Car* bcc = bcf->createCar(); Bus* bcb = bcf->createBus(); bcc->name(); bcb->name(); return 0; }