设计模式-----工厂方法模式

设计模式-----工厂方法模式,第1张

1.定义

工厂方法模式定义了一个用于创建对象的接口,让子类决定要实例化哪一个类,也就是说工厂模式让实例化推迟到子类。

2.UML类图

3.代码实现 

#include 
#include 
using namespace std;

class Operation
{
public:
	double numberA, numberB;
	virtual double  getResult()
	{
		return 0;
	}
};

class addOperation :public Operation
{
	double getResult()
	{
		return numberA + numberB;
	}
};


class subOperation :public Operation
{
	double getResult()
	{
		return numberA - numberB;
	}
};

class mulOperation :public Operation
{
	double getResult()
	{
		return numberA*numberB;
	}
};

class divOperation :public Operation
{
	double getResult()
	{
		return numberA / numberB;
	}
};

class IFactory
{
public:
	virtual Operation *createOperation() = 0;
};

class AddFactory :public IFactory
{
public:
	static Operation *createOperation()
	{
		return new addOperation();
	}
};


class SubFactory :public IFactory
{
public:
	static Operation *createOperation()
	{
		return new subOperation();
	}
};

class MulFactory :public IFactory
{
public:
	static Operation *createOperation()
	{
		return new mulOperation();
	}
};

class DivFactory :public IFactory
{
public:
	static Operation *createOperation()
	{
		return new divOperation();
	}
};

int main()
{
	Operation *oper = MulFactory::createOperation();//由客户端来决定实例化哪一个工厂来实现运算类
	oper->numberA = 9;
	oper->numberB = 99;
	cout << oper->getResult() << endl;
	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/707361.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存