您的位置:首页 > 编程语言

设计模式——工厂模式

2017-06-10 15:10 330 查看
问题描述:
使用工厂模式实现简单计算器的加减乘数功能。

github地址:https://github.com/lining91/FactoryPattern2

工厂方法模式,定义了一个用于创建对象的接口,封装对象的创建,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类中。

**与简单工厂的区别:**

简单工厂模式的优点是工厂类中包含了必要的逻辑判断,根据增加需求来动态的实例化相关的类,去除了与具体产品的依赖。
在简单工厂模式中,当增加需求时,需要修改原有的工厂类,增加新的类,对扩展开放了,对修改也开放了,违背了开放-封闭原则。
工厂模式中,当增加需求时,不需要修改原有的工厂类,只需要增加此类需求的类和相应的工厂类即可。符合开放-封闭原则。

**代码如下:**
操作类如下


//  操作基类
class Operation{
public:
virtual int GetResult( int n1, int n2 ) = 0;
};

//  加减乘数类
class OperationAdd : public Operation{
public:
virtual int GetResult(int n1, int n2)
{
return n1 + n2;
}
};

class OperationSub : public Operation{
public:
virtual int GetResult(int n1, int n2)
{
return n1 - n2;
}
};

class OperationMul : public Operation{
public:
virtual int GetResult(int n1, int n2)
{
return n1 * n2;
}
};

class OperationDiv : public Operation{
public:
virtual int GetResult(int n1, int n2)
{
if (n2 == 0)
throw "除数不能为0!";
return n1 / n2;
}
};


工厂抽象类和工厂具体类:


//  抽象工厂类
class IFactory
{
public:
virtual Operation* CreateOperation() = 0;
};

//  具体工厂类
class AddFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationAdd();
}
};

class SubFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationSub();
}
};

class MulFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationMul();
}
};

class DivFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationDiv();
}
};


main 函数:


void main()
{
int n1 = 33;
int n2 = 52;

//  创建具体操作工厂类,如果需要修改新的计算方式,需要重新生成该类
IFactory* pFactory = new MulFactory();
if ( pFactory == NULL )
return;

Operation* pOpe = pFactory->CreateOperation();
if (pOpe == NULL)
return;

try{
int nResult = pOpe->GetResult(n1, n2);
cout << n1 << " * " << n2 << " is " << nResult << endl;
}
catch(char* pErr)
{
cout << pErr << endl;
}
delete pOpe;
pOpe = NULL;
delete pFactory;
pFactory = NULL;

system("pause");
}


运行结果如下:



当需要修改乘法运算为“+”运算时,只需要重新生成main函数中的IFactory* pFactory实例。降低代码的耦合度,对其余代码没有影响。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息