简单工厂模式
详细介绍请见:★★★原文链接★★★:https://subingwen.cn/design-patterns/simple-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;
}
};
// 定义强枚举类型
enum class Type :char { Sheep, Lion, Bat };
// 定义工厂类
class SmileFactory {
public:
// 把工厂函数的返回值设置成 父类指针类型,返回一个指向子类对象的父类指针(实现了多态)
AbstractSmile* createSmile(Type type) {
AbstractSmile* ptr = nullptr;
switch (type)
{
case Type::Sheep:
ptr = new SheepSmile;
break;
case Type::Lion:
ptr = new LionSmile;
break;
case Type::Bat:
ptr = new BatSmile;
break;
default:
break;
}
return ptr;
}
};
int main() {
// 创建工厂类对象
SmileFactory* factory = new SmileFactory;
AbstractSmile* obj = factory->createSmile(Type::Lion);
obj->transform();
obj->ability();
return 0;
}
res:
多态需要满足的3个条件:
1. 类和类之间有继承关系
2. 父类中有虚函数,并且在子类中重写虚函数
3. 使用父类指针或引用指向子类对象
详细介绍请见:★★★原文链接★★★:https://subingwen.cn/design-patterns/simple-factory/
(〃>_<;〃)(〃>_<;〃)(〃>_<;〃)
标签:设计模式,子类,transform,模式,工厂,AbstractSmile,virtual,父类 From: https://www.cnblogs.com/wjjgame/p/17658359.html