总结两者的实现代码区别
简单工厂模式代码策略模式代码main函数调用代码区别
简单工厂模式代码
CashSuper
* CashFactory
::createCashAccept(char type
) {
CashSuper
*cs
= NULL;
switch (type
) {
case 'n':
cs
= new CashNormal();
break;
case 'r':
cs
= new CashReturn(300, 100);
break;
case 'c':
cs
= new CashRebate(0.8);
break;
}
return cs
;
}
策略模式代码
class CashContext
{
private:
CashSuper
*cs
;
public:
CashContext(char type
) {
switch (type
) {
case 'n':
cs
= (new CashNormal());
break;
case 'r':
cs
= (new CashReturn(300, 100));
break;
case 'c':
cs
= (new CashRebate(0.8));
break;
}
}
double GetResult(double money
) {
return cs
->acceptCash(money
);
}
};
main函数调用
int main()
{
double total
= 0.0;
CashFactory csfactory
;
CashSuper
*csuper
= csfactory
.createCashAccept('r');
total
= csuper
->acceptCash(1000);
}
int main()
{
double total
=0.0;
CashContext
*cc
= new CashContext('r');
total
= cc
->GetResult(1000);
}
代码区别
简单工厂模式只是用Factory类创建具体的对象,并且返回对象,并不对对象进行封装。主函数调用时,还需要创建相应对象去指向简单工厂模式返回的对象。 策略模式则使用Context类中的GetResult函数封装了具有类似功能算法的类。主函数调用时,只需要创建Context类就好了。