现在的位置: 首页 > 综合 > 正文

简单工厂模式

2013年12月13日 ⁄ 综合 ⁄ 共 765字 ⁄ 字号 评论关闭

#include <iostream>
#include<string>
#include <math.h>
using namespace std;

//抽象支付类
class AbstractPay
{
public:
virtual void pay()=0;
};

//具体支付类
class CashPay: public AbstractPay
{
public:
void pay()
{
cout<<"PAYBYCASH"<<endl;
}
CashPay()
{
cout<<"PAYBYCASH"<<endl;
}

};

class CreditCard:public AbstractPay
{
public:
void pay()
{
cout<<"PAYBYCREITCARD"<<endl;
}
};

//支付工厂
class PayMethodFactory
{
public:
static AbstractPay* getPayMethod(string type)
{
if(type == "cash")
{
return new CashPay();
}
else if(type == "card")
{
return new CreditCard();
}
else
{
return 0;
}
}

};

int main()
{
string str = "";
cout<<"Please input the names"<<endl;
cin>>str;
do
{
PayMethodFactory *fac = new PayMethodFactory();
AbstractPay *psy = fac->getPayMethod(str);
if(psy !=0)
{
psy->pay();
cout<<"If you want to exit,type 'n'";
cin>>str;
}
else
{
break;
}

}while(str !="n");

system("pause");
return 0;
}

抱歉!评论已关闭.