简单工厂模式的弊端
简单工厂模式虽然简单,但是违反了设计模式中的开放封闭原则
,即工厂类在数据增加时需要被修改,而我们在设计时对于已经设计好的类需要避免修改的操作,而选用扩展的方式。
工厂模式设计
简单工厂模式只有一个工厂类,而工厂模式是有一个基类,多个子类,基类中包含一个虚工厂函数,多个子类重写父类的工厂函数。每个子工厂类负责生产一种类,这相当于再次解耦,将工厂类再次拆分细化。
代码实例
cpp
#include <iostream>
using namespace std;
//创建父类
class AbstructSmile
{
public:
virtual void transform() = 0;
virtual void ability() = 0;
virtual ~AbstructSmile() {} //提供虚析构函数,为了能够释放子类对象
};
class sheepSmile : public AbstructSmile
{
public:
void transform() override
{
cout << "山羊恶魔果实" << endl;
}
void ability() override
{
cout << "山羊能力" << endl;
}
};
class lionSmile : public AbstructSmile
{
public:
void transform() override
{
cout << "狮子恶魔果实" << endl;
}
void ability() override
{
cout << "狮子能力" << endl;
}
};
class batSmile : public AbstructSmile
{
public:
void transform() override
{
cout << "蝙蝠恶魔果实" << endl;
}
void ability() override
{
cout << "蝙蝠能力" << endl;
}
};
enum class Type :char {SHEEP,LION,BAT};
//创建工厂类--->基类
class smileFactory
{
public:
virtual ~smileFactory() {}
virtual AbstructSmile* creatsmile() = 0;
};
class sheepFactory : public smileFactory
{
public:
AbstructSmile* creatsmile() override
{
return new sheepSmile;
}
~sheepFactory()
{
cout << "sheepFactory 被析构了" << endl;
}
};
class lionFactory : public smileFactory
{
public:
AbstructSmile* creatsmile() override
{
return new lionSmile;
}
~lionFactory()
{
cout << "lionFactory 被析构了" << endl;
}
};
class batFactory : public smileFactory
{
public:
AbstructSmile* creatsmile() override
{
return new batSmile;
}
~batFactory()
{
cout << "batFactory 被析构了" << endl;
}
};
int main()
{
smileFactory* sheepPtr = new sheepFactory;
AbstructSmile* sheepObj = (AbstructSmile*)(sheepPtr->creatsmile());
sheepObj->transform();
sheepObj->ability();
smileFactory* lionPtr = new lionFactory;
AbstructSmile* lionObj = (AbstructSmile*)(lionPtr->creatsmile());
lionObj->transform();
lionObj->ability();
smileFactory* batPtr = new batFactory;
AbstructSmile* batObj = (AbstructSmile*)(batPtr->creatsmile());
batObj->transform();
batObj->ability();
delete sheepObj;
delete sheepPtr;
delete lionObj;
delete lionPtr;
delete batObj;
delete batPtr;
return 0;
}
抽象类
抽象类不能直接构造对象,因为他是一种抽象的概念,没有具体的实现,如果想对象一个对象,需要创建一个继承自抽象类的具体类,并在该类中实现所有的纯虚函数,然后可以构造该具体类。