策略模式(strategy):它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
个人理解:使用类C操控类A继承体系A1,A2,A3中公有对外暴露接口。
v1 存在的问题
v1 重构方向
main.cpp
#include "Sales.h"void test()
{/* 当前顾客购买的货物 */Goods* g1 = new Goods(1000, 1, eNormal);Goods* g2 = new Goods(2000, 2, e8);Goods* g3 = new Goods(3000, 3, e7);Goods* g4 = new Goods(4000, 4, e5);/* 进入销售系统结算 */list<Goods* > lGoods = { g1, g2, g3, g4 };Sales* pSales = new Sales(lGoods);cout << setiosflags(ios::fixed) << setprecision(2);cout << "------------------------------------------------" << endl;cout << "购物清单:nn" << pSales->getGoodsList() << endl;cout << "总价:" << pSales->getTotalPrice() << " 元" << endl << endl;cout << "------------------------------------------------" << endl;/* 析构 */delete pSales;pSales = nullptr;
}int main()
{test();system("pause");return 0;
}
4.2.1 Goods.h
#pragma onceenum PriceDiscount
{eNormal = 0,//正常收费e8,//打八折e7,//打7折e5//打5折
};/* 商品类 */
struct Goods
{
public:Goods() :price(0.0), count(0), discount(eNormal) {}Goods(const double& _price, const int& _count, const PriceDiscount& _discount) :price(_price), count(_count), discount(_discount) {}
public:double price;int count;PriceDiscount discount;
};
4.2.1 Sales.h
#pragma once
#include "Goods.h"
#include <string>
#include <list>
#include <iomanip>
#include <sstream>
using namespace std;string double2string(const double& num ,int precision)
{std::stringstream ssPrice;ssPrice << std::setiosflags(std::ios::fixed) << std::setprecision(precision) << num;return ssPrice.str();
}/* 销售系统类 */
class Sales
{
public:Sales(const list<Goods* >& lGoods);~Sales();double getTotalPrice() { return m_dTotalPrice; }string getGoodsList() { return m_sGoodsList; }
private:void calcTotalPriceAndGoodsList(double& totalPrice, string& goodsList);
public:list<Goods* > m_lGoods;double m_dTotalPrice;string m_sGoodsList;
};Sales::Sales(const list<Goods* >& lGoods) :m_lGoods(lGoods)
{calcTotalPriceAndGoodsList(m_dTotalPrice, m_sGoodsList);
}Sales::~Sales()
{for each (auto goods in m_lGoods){delete goods;goods = nullptr;}
}void Sales::calcTotalPriceAndGoodsList(double& totalPrice, string& goodsList)
{totalPrice = 0.0;goodsList = "";for each (auto goods in m_lGoods){double price = goods->price;int n = goods->count;PriceDiscount discount = goods->discount;double tmpPrice = price*n;string strDiscount;switch (discount){case eNormal:strDiscount = "正常";break;case e8:strDiscount = "打8折";tmpPrice *= 0.8;break;case e7:strDiscount = "打7折";tmpPrice *= 0.7;break;case e5:strDiscount = "打5折";tmpPrice *= 0.5;break;default:break;}totalPrice += tmpPrice;string tmpList = "单价:" + double2string(price, 2) + "t数量:" + to_string(n) + "t" + strDiscount + "t合计:" + double2string(tmpPrice, 2) + " 元n";goodsList += tmpList;}return;
}
《大话设计模式》C++实现:02 策略模式(四)——(策略模式+简单工厂)
此为《大话设计模式》学习心得系列 P18~~
本文发布于:2024-02-02 04:53:44,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170682082541484.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |