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; } }