创建型模式 抽象工厂
/** * 创建型模式 抽象工厂 * 抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,能够创建多个产品族的产品对象。 * * 抽象工厂(Creator)角色 * 抽象工厂模式的核心,包含对多个产品结构的声明,任何工厂类都必须实现这个接口。 * 具体工厂( Concrete Creator)角色 * 具体工厂类是抽象工厂的一个实现,负责实例化某个产品族中的产品对象。 * 抽象(Product)角色 * 抽象模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。 * 具体产品(Concrete Product)角色 * 抽象模式所创建的具体实例对象 * */#includeclass Fruit{public: virtual void sayname() { std::cout << "I'am fruit" << std::endl; } virtual ~Fruit() {}};class FruitFactory{public: virtual Fruit * CreateBanana() { return new Fruit(); } virtual Fruit * CreatePear() { return new Fruit(); } virtual ~FruitFactory() {}};class SouthBanana: public Fruit{public: virtual void sayname() override { std::cout << "South Banana" << std::endl; }};class NorthBanana: public Fruit{public: virtual void sayname() override { std::cout << "North Banana" << std::endl; }};class SouthPear: public Fruit{public: virtual void sayname() override { std::cout << "South Pear" << std::endl; }};class NorthPear: public Fruit{public: virtual void sayname() override { std::cout << "North Pear" << std::endl; }};// 在C++中,只要原来的返回类型是指向类的指针或引用,新的返回类型是指向派生类的指针或引用,覆盖的方法就可以改变返回类型。这样的类型称为协变返回类型(Covariant returns type).class SouthFactory: public FruitFactory{public: virtual SouthBanana * CreateBanana() override { return new SouthBanana(); } virtual SouthPear * CreatePear() override { return new SouthPear(); }};// 在C++中,只要原来的返回类型是指向类的指针或引用,新的返回类型是指向派生类的指针或引用,覆盖的方法就可以改变返回类型。这样的类型称为协变返回类型(Covariant returns type).class NorthFactory: public FruitFactory{public: virtual NorthBanana * CreateBanana() override { return new NorthBanana(); } virtual NorthPear * CreatePear() override { return new NorthPear(); }};void mytest(){ FruitFactory * factory = nullptr; Fruit * fruit = nullptr; factory = new SouthFactory(); fruit = factory->CreateBanana(); fruit->sayname(); delete fruit; fruit = nullptr; fruit = factory->CreatePear(); fruit->sayname(); delete fruit; fruit = nullptr; delete factory; factory = nullptr; factory = new NorthFactory(); fruit = factory->CreateBanana(); fruit->sayname(); delete fruit; fruit = nullptr; fruit = factory->CreatePear(); fruit->sayname(); delete fruit; fruit = nullptr; delete factory; factory = nullptr; return;}int main(){ mytest(); system("pause"); return 0;}