C++设计模式从0进击-1-简单(静态)工厂模式
2017-01-18 13:01
441 查看
简单工厂模式的工厂类一般是使用静态方法,通过接收的参数的不同来返回不同的对象实例。
不修改代码的话,是无法扩展的。
[cpp] view
plain copy
print?
#include <iostream>
using namespace std;
class COperation
{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
double dResult = 0;
return dResult;
}
};
//加法
class AddOperation: public COperation
{
virtual double GetResult()
{
return m_nFirst+ m_nSecond;
}
};
//减法
class SubOperation: public COperation
{
public:
virtual double GetResult()
{
return m_nFirst - m_nSecond;
}
};
[cpp] view
plain copy
print?
//工厂类
[cpp] view
plain copy
print?
class CCaculatorFactory
{
public:
static COperation * Create(char cOperator);
};
COperation * CCaculatorFactory::Create(char cOperator)
{
COperation * oper;
switch(cOperator)
{
case '+':
oper = new AddOperation();
break;
case '-':
oper = new SubOperation();
break;
default:
oper = new AddOperation();
break;
}
return oper;
}
[cpp] view
plain copy
print?
int _tmain(int argc, _TCHAR * argv [])
{
int a, b;
cin >> a >> b;
COperation * op = CCaculatorFactory::Create('-');
op->m_nFirst = a;
op->m_nSecond = b;
cout << op->GetResult() << endl;
return 0;
}
不修改代码的话,是无法扩展的。
[cpp] view
plain copy
print?
#include <iostream>
using namespace std;
class COperation
{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
double dResult = 0;
return dResult;
}
};
//加法
class AddOperation: public COperation
{
virtual double GetResult()
{
return m_nFirst+ m_nSecond;
}
};
//减法
class SubOperation: public COperation
{
public:
virtual double GetResult()
{
return m_nFirst - m_nSecond;
}
};
[cpp] view
plain copy
print?
//工厂类
[cpp] view
plain copy
print?
class CCaculatorFactory
{
public:
static COperation * Create(char cOperator);
};
COperation * CCaculatorFactory::Create(char cOperator)
{
COperation * oper;
switch(cOperator)
{
case '+':
oper = new AddOperation();
break;
case '-':
oper = new SubOperation();
break;
default:
oper = new AddOperation();
break;
}
return oper;
}
[cpp] view
plain copy
print?
int _tmain(int argc, _TCHAR * argv [])
{
int a, b;
cin >> a >> b;
COperation * op = CCaculatorFactory::Create('-');
op->m_nFirst = a;
op->m_nSecond = b;
cout << op->GetResult() << endl;
return 0;
}
相关文章推荐
- C++设计模式从0进击-1-简单(静态)工厂模式
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)zz
- C++设计模式-----简单工厂
- 设计模式C++版_1_简单工厂模式
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- [转]C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- 小猪学设计模式——工厂模式之简单工厂(静态工厂)
- C++设计模式学习笔记一:简单工厂模式
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- c++设计模式之简单工厂
- 设计模式之简单工厂模式:c++实现
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- C++设计模式之简单工厂模式
- C++设计模式之简单工厂模式
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- .C++设计模式之一 工厂模式(简单工厂、工厂和抽象工厂)
- c++设计模式之简单工厂模式
- 设计模式:浅析 抽象工厂、工厂方法、简单(静态)工厂 java实现