编程语言
首页 > 编程语言> > C++工厂模式

C++工厂模式

作者:互联网

意图

定义一个用于创建对象的接口,让子类决定实例化哪一个类。Facotry Method 使一个类的实例化延迟到其子类。

适用性

示意性代码

#include <iostream>

using namespace std;

class Product {

};

class ConcreteProductA : public Product {

};

class ConcreteProductB : public Product {

};

class Creator {
public:
    virtual Product* FactoryMethod() = 0;
};

class ConcreteCreatorA : public Creator {
    Product* FactoryMethod() override {
        return new ConcreteProductA();
    }
};

class ConcreteCreatorB : public Creator {
    Product* FactoryMethod() override {
        return new ConcreteProductB();
    }
};

class Client {
private:
    Product* _product;

public:
    Client(Creator* creator) {
        _product = creator->FactoryMethod();
    }

    ~Client() {
        delete _product;
    }
};

int main() {
    Creator* creator = new ConcreteCreatorB();
    Client client(creator);
}

标签:Product,Creator,子类,FactoryMethod,模式,public,C++,工厂,class
来源: https://www.cnblogs.com/jerry-1015/p/16521202.html