1. 案例:营业员根据客户所购买商品的单价和数量,根据不同活动向客户收费
- 正常原价收费
- 八折收费
- 满300返100
2. 简单工厂模式结构
- 抽象产品(Abstract Product):具体产品类的基类,包含创建产品的公共方法
enum CashType { NORMAL = 0, REBATE, RETURN }; class CashSuper { public: virtual double AcceptCash(double dMoney) = 0; };
- 具体产品(Concrete Product):抽象产品的派生类,包含具体产品特有的实现方法,是简单工厂模式的创建目标
class CashNormal : public CashSuper { public: // 通过 CashSuper 继承 double AcceptCash(double dMoney) override; }; double CashNormal::AcceptCash(double dMoney) { return dMoney; }
class CashRebate : public CashSuper { public: CashRebate(double dMoneyRebate); // 通过 CashSuper 继承 double AcceptCash(double dMoney) override; private: double m_dMoneyRebate; }; CashRebate::CashRebate(double dMoneyRebate): m_dMoneyRebate(dMoneyRebate) { } double CashRebate::AcceptCash(double dMoney) { return dMoney * m_dMoneyRebate; }
class CashReturn : public CashSuper { public: CashReturn(double dMoneyCondition, double dMoneyReturn); // 通过 CashSuper 继承 double AcceptCash(double dMoney) override; private: double m_dMoneyCondition; double m_dMoneyReturn; }; CashReturn::CashReturn(double dMoneyCondition, double dMoneyReturn): m_dMoneyCondition(dMoneyCondition), m_dMoneyReturn(dMoneyReturn) { } double CashReturn::AcceptCash(double dMoney) { if (fabs(m_dMoneyCondition) < 1e-6) return dMoney; return dMoney - floor(dMoney / m_dMoneyCondition) * m_dMoneyReturn; }
- 工厂(Factory):根据客户提供的具体产品类的参数,创建具体产品实例
class CashFactory { public: static std::shared_ptr<CashSuper> CreatCashOperation(CashType eCashType); }; std::shared_ptr<CashSuper> CashFactory::CreatCashOperation(CashType eCashType) { switch (eCashType) { case NORMAL: return std::make_shared<CashNormal>(); break; case REBATE: return std::make_shared<CashRebate>(0.8); break; case RETURN: return std::make_shared<CashReturn>(300.0, 100.0); break; default: return std::make_shared<CashNormal>(); break; } }
标签:dMoneyCondition,return,double,AcceptCash,dMoney,工厂,模式,简单,public From: https://www.cnblogs.com/BoYuCG/p/18415992