【C++学习笔记】十、C++设计模式-抽象工厂模式

文章目录

  • 1 抽象工厂
  • 2 客户端的调用

整个结构示意如下:

抽象类只做接口,不做实现,所有具体实现都是集成其抽象类。

AbstractFactory ProductA ProductB ConcreteProductA1 ConcreteProductA2 ConcreteProductB1 ConcreteProductB2 ConcreteFactory1 ConcreteFactory2 Inherits Inherits Inherits Inherits Inherits Inherits herits herits

1 抽象工厂

抽象类只做接口,不做实现

定义抽象产品


// 抽象产品类
class ProductA {
public:
    virtual void doSomething() = 0;
};

class ProductB {
public:
    virtual void doSomething() = 0;
};

定义具体产品类: 产品实际实现

// 具体产品类
class ConcreteProductA1 : public ProductA {
public:
    void doSomething() override { cout << "ConcreteProductA1 do something." << endl; }
};

class ConcreteProductA2 : public ProductA {
public:
    void doSomething() override { cout << "ConcreteProductA2 do something." << endl; }
};

class ConcreteProductB1 : public ProductB {
public:
    void doSomething() override { cout << "ConcreteProductB1 do something." << endl; }
};

class ConcreteProductB2 : public ProductB {
public:
    void doSomething() override { cout << "ConcreteProductB2 do something." << endl; }
};
// 抽象工厂类
class AbstractFactory {
public:
    virtual ProductA* createProductA() = 0;
    virtual ProductB* createProductB() = 0;
};

// 具体工厂类
class ConcreteFactory1 : public AbstractFactory {
public:
    ProductA* createProductA() override { return new ConcreteProductA1(); }
    ProductB* createProductB() override { return new ConcreteProductB1(); }
};

class ConcreteFactory2 : public AbstractFactory {
public:
    ProductA* createProductA() override { return new ConcreteProductA2(); }
    ProductB* createProductB() override { return new ConcreteProductB2(); }
};

2 客户端的调用

// 客户端代码
int main() {
    //创建工厂1
    AbstractFactory* factory = new ConcreteFactory1();
	//创建对应的产品
    ProductA* productA = factory->createProductA();
    ProductB* productB = factory->createProductB();
    //产品中的方法实现
    productA->doSomething();
    productB->doSomething();

    //销毁产品
    delete productA;
    delete productB;

    //创建工厂2
    factory = new ConcreteFactory2();
    //工厂2中创建对应的产品
    productA = factory->createProductA();
    productB = factory->createProductB();

    //产品中的方法实现
    productA->doSomething();
    productB->doSomething();

    //销毁产品和工厂
    delete productA;
    delete productB;
    delete factory;

    return 0;
}

你可能感兴趣的:(C++学习笔记,c++,学习,设计模式)