有一个销售管理系统支持多种支付方式,如现金支付,信用卡支付,代金券支付等,在设计过如果不使用简单工厂模式,可能会存在如下的支付方式。
void pay(string pay_type)
{
if(pay_type==现金)
{
现金支付处理手段
}
else if(pay_type==信用卡)
{
信用卡支付处理
}
else if(pay_type==代金券)
{
代金券处理
}
........
}
class AbstractPay
{
public:
virtual void pay() = 0;
};
class CashPay :public AbstractPay
{
public:
CashPay()
{
}
void pay()
{
cout << "现金支付" << endl;
}
};
class CreditcardPay :public AbstractPay
{
public:
CreditcardPay()
{
}
void pay()
{
cout << "信用卡支付" << endl;
}
};
class PayMethodFactory
{
public:
static AbstractPay* getPayMethod(string type)
{
if (type == "cash")
{
return new CashPay;
}
else
{
return new CreditcardPay;
}
}
};
int main()
{
PayMethodFactory *pmf = new PayMethodFactory; //基类指针指向带有虚函数的派生类对象形成多态
AbstractPay* p = pmf->getPayMethod("cash");
//假定现在是现金支付
p->pay();
system("pause");
return 0;
}
class DBFactory
{
public:
virtual Statement* getStatement(void) = 0;
virtual Connection* getConnection(void) = 0;
};
class Statement
{
public:
virtual void ExeStatement() = 0;
};
class Connection
{
virtual void InConnection() = 0;
};
class OracleConnetcion :public Connection
{
public:
void InConnection()
{
cout << "Oracle正在连接" << endl;
}
};
class MySqlConnection :public Connection
{
public:
void InConnection()
{
cout << "MySql 正在连接" << endl;
}
};
class OracleStatement :public Statement
{
public:
void ExeStatement()
{
cout << "Oracle正在执行" << endl;
}
};
class MySqlStatement :public Statement
{
public :
void ExeStatement()
{
cout << "MySql正在执行" << endl;
}
};
int main()
{
DBFactory *dbf = new MySqlFactory;
Statement* st=dbf->getStatement();
st->ExeStatement();
system("pause");
}