C++工厂方法模式讲解和代码示例

2023-05-30,,

在C++中使用模式

使用示例: 工厂方法模式在 C++ 代码中得到了广泛使用。 当你需要在代码中提供高层次的灵活性时, 该模式会非常实用。

识别方法: 工厂方法可通过构建方法来识别, 它会创建具体类的对象, 但以抽象类型或接口的形式返回这些对象。

main.cpp概念示例

/*
Product接口声明了所有具体产品必须实现的操作。
*/
class Product{
public:
virtual ~Product() {}
virtual std::string Operation() const = 0 ;
}; /*
具体的产品提供了Product接口的各种实现
*/
class ConcreteProduct1:public Product{
public:
std::string Operation() const override {
return "{Result of the ConcreteProduct1}";
}
}; clss ConcreteProduct2:public Product{
public:
std::string Operation() const override{
return "{Result of the ConcretProduct2}";
}
}; /*
Creator类声明了工厂方法,该方法应该返回Product类的一个对象。创建者的子类通常提供此方法的实现。
*/
class Creator{
/*注意,创建者还可能提供工厂方法的一些默认实现*/
public:
virtual ~Creator() {};
virtual Product * FactoryMethod() const = 0;
/*
还要注意,尽管它的名字,创建者的主要职责不是创建产品。通常,它包含一些核心业务逻辑,
这些逻辑依赖于由工厂方法返回的Product对象。子类可以间接地改变这一业务逻辑通过覆盖工厂方法返回一个不同类型的产品。
*/
std::string SomeOperation() const {
/*调用工厂方法来创建Product对象*/
Product *product = this->FactoryMethod();
/*现在就可以使用product了*/
std::string result = "Creator: The same creator 's code has just worked with " + product->Operation();
delete product;
return result;
} }; /*
具体的创建者覆盖工厂方法以更改结果产品的类型。
*/
class ConcreteCreator1 : public Creator{
/*
注意,方法的签名仍然使用抽象产品类型,即使具体产品实际上是从方
法返回的。这样创建者就可以独立于具体的产品类。
*/
public:
Product * FactoryMethod() const override{
return new ConcreteProduct1();
}
}; class ConcreteCreator2 : public Creator{
public:
Product * FactoryMethod() const override{
return new ConcreteProduct2();
}; /*
客户端代码与具体创建者的实例一起工作,尽管是通过其基本接口进行的。只要客户端保持与创建者通过基础界面,您可以通过它的创造者的子类。
*/
void ClientCode(const Creator & creator){
std::cout << "Client: I'm not aware of the creator's class, but it still works.\n" << creator.SomeOperation() <<std::endl; } /*应用程序根据配置或环境选择创建者的类型*/
int main() {
std::cout << "App: Launched with the ConcreteCreator1.\n";
Creator* creator = new ConcreteCreator1();
ClientCode(*creator);
std::cout << std::endl;
std::cout << "App: Launched with the ConcreteCreator2.\n";
Creator* creator2 = new ConcreteCreator2();
ClientCode(*creator2); delete creator;
delete creator2;
return 0;
}

执行结果如下:

App: Launched with the ConcreteCreator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct1} App: Launched with the ConcreteCreator2.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with {Result of the ConcreteProduct2}

C++工厂方法模式讲解和代码示例的相关教程结束。

《C++工厂方法模式讲解和代码示例.doc》

下载本文的Word格式文档,以方便收藏与打印。