一 典型工厂方法模式(Factory Method)结构图
二 典型工厂模式实现
测试代码
#include <iostream>
using namespace std;
class Product{
public:
string name;
virtual void show(){
cout << "我是:";
}
};
class Desk : public Product
{
public:
Desk(){
name = "桌子";
}
void show(){
Product::show();
cout << name << endl;
}
};
class Cup : public Product
{
public:
Cup(){
name = "杯子";
}
void show(){
Product::show();
cout << name << endl;
}
};
class IFactory{
public:
virtual Product* createProduct() = 0;
};
class DeskFactory : public IFactory{
public:
Product* createProduct(){
return new Desk();
}
};
class CupFactory : public IFactory{
public:
Product* createProduct(){
return new Cup();
}
};
int main()
{
IFactory *ifactory = new DeskFactory();
Product *product = ifactory->createProduct();
product->show();
IFactory *ifactory_2 = new CupFactory();
Product *product_2 = ifactory_2->createProduct();
product_2->show();
return 0;
}
测试结果:
我是:桌子
我是:杯子
参考:https://lkmao.blog.csdn.net/article/details/128952843