★★★原文链接★★★:https://subingwen.cn/design-patterns/factory/
工厂模式
简单工厂 工厂和对象的关系:一对多
工厂模式 工厂和对象的关系:一对一
示例:
#include <iostream>
using namespace std;
// 产品类的父类 - 人造恶魔果实父类
class AbstractSmile {
public:
virtual void transform() = 0;
virtual void ability() = 0;
virtual ~AbstractSmile() {} // 虚析构函数
};
// 1
class SheepSmile :public AbstractSmile
{
public:
void transform() override { // override检查子类重写的虚函数的名字和父类的是否相同(相同是正确的)
cout << "SheepSmile transform" << endl;
}
void ability() override {
cout << "SheepSmile ability" << endl;
}
};
// 2
class LionSmile :public AbstractSmile
{
public:
void transform() override { // override检查子类重写的虚函数的名字和父类的是否相同(相同是正确的)
cout << "LionSmile transform" << endl;
}
void ability() override {
cout << "LionSmile ability" << endl;
}
};
// 3
class BatSmile :public AbstractSmile
{
public:
void transform() override { // override检查子类重写的虚函数的名字和父类的是否相同(相同是正确的)
cout << "BatSmile transform" << endl;
}
void ability() override {
cout << "BatSmile ability" << endl;
}
};
// 定义工厂类 - 抽象父类
class AbstractFactory {
public:
virtual AbstractSmile* createSmile() = 0;
virtual ~AbstractFactory(){}
};
// 生产SheepSmile
class SheepFactory :public AbstractFactory
{
public:
AbstractSmile* createSmile() {
return new SheepSmile;
}
~SheepFactory() {
cout << "SheepFactory 析构函数调用" << endl;
}
};
// 生产LionSmile
class LionFactory :public AbstractFactory
{
public:
AbstractSmile* createSmile() {
return new LionSmile;
}
~LionFactory() {
cout << "LionFactory 析构函数调用" << endl;
}
};
// 生产BatSmile
class BatFactory :public AbstractFactory
{
public:
AbstractSmile* createSmile() {
return new BatSmile;
}
~BatFactory() {
cout << "BatFactory 析构函数调用" << endl;
}
};
int main() {
// 创建工厂类对象
AbstractFactory* factory = new LionFactory;
AbstractSmile* obj = factory->createSmile();
obj->transform();
obj->ability();
delete factory;
delete obj;
return 0;
}
res:
工厂模式的“工厂”:
1. 一个基类,包含一个虚工厂函数,用于实现多态。
2. 多个子类,重写父类的工厂函数。
★★★原文链接★★★:https://subingwen.cn/design-patterns/factory/
(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)
标签:factory,设计模式,transform,virtual,工厂,AbstractSmile,模式,父类 From: https://www.cnblogs.com/wjjgame/p/17661089.html