设计模式--简单工厂模式示例代码

简单工厂模式:

简单工厂模式按照设计模式类型分的话是属于创建型模式,他是工厂模式中最简单的一种,他不属于GoF 23中设计模式之一,但是是简单实用的。他是有一个工厂对象来决定创建哪一种对象的实例。

/*适用场景
1.工厂类负责创建的对象比较少,由于创建的对象较少,不会造成工厂方法中的业务逻辑太过复杂
2.客户只知道传入工厂类的参数,对于如何创建对象并不关心。
*/

优点:外界只要传入类的名字或者识别符即可,不需要关心具体创建过程,只顾“消费”就可以了。各有各的指责和权力,分工明确,利于整个软件架构优化。

缺点:违反里高内聚责任分配原则,将全部逻辑放到一个工厂类中,如果需要支持新的类,那就必须改变工厂类了。

例子:

代码中有抽象水果类,具体水果类

工厂类:工厂类负责创建水果的对象,而不是具体的去调用各个水果类创建


#include 
using namespace std;

//抽象水果类
class AbstractFruit
{
public:
	virtual void SetFruit() = 0;
};


class apple : public AbstractFruit
{
public:
	virtual void SetFruit()
	{
		cout << "苹果" << endl;
	}
};

class banana : public AbstractFruit
{
public:
	virtual void SetFruit()
	{
		cout << "香蕉" << endl;
	}
};

class pear : public AbstractFruit
{
public:
	virtual void SetFruit()
	{
		cout << "鸭梨" << endl;
	}
};

class FruitFactory {
public:
	static AbstractFruit* CreateFruit(string flag)
	{
		if (flag == "apple")
			return new apple;
		else if (flag == "banana")
			return new banana;
		else if (flag == "pear")
			return new pear;
		else
			return NULL;
	}

};

void test()
{
	FruitFactory* Factory = new FruitFactory;
	AbstractFruit* fruit = Factory->CreateFruit("apple");
	fruit->SetFruit();
	delete fruit;

	fruit = Factory->CreateFruit("banana");
	fruit->SetFruit();
	delete fruit;

	fruit = Factory->CreateFruit("pear");
	fruit->SetFruit();
	delete fruit;

}


int main()
{
	test();
	return 0;
}

 

你可能感兴趣的:(设计模式,设计模式,简单工厂模式)