• 策略模式


    策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。从这些类中抽象出公共接口。策略模式让算法独立于使用它的客户而独立变化。

    //图书折扣策略的抽象类
    class CBookStrategy
    {
    public:
    	virtual double GetDiscount()=0;
    	CBookStrategy()
    	{
    	
    	}
    };
    //无折扣
    class CNonDiscount: public CBookStrategy
    {
    private:
    	int     m_BookCount;
    	double  m_BookPrice;
    public:
    	CNonDiscount(int BookCount,double BookPrice)
    	{
    		m_BookCount = BookCount;
    		m_BookPrice = BookPrice;
    	}
    	virtual double GetDiscount()
    	{
    		return m_BookCount*m_BookPrice;
    	}
    };
    
    //按百分比折扣
    class CPerDiscount : public CBookStrategy
    {
    private:
    	int     m_BookCount;
    	double  m_BookPrice;
    	double  m_Percent;
    public:
    	double GetPercent()
    	{
    		return m_Percent;
    	}
    	void SetPercent(double Percent)
    	{
    		m_Percent = Percent;
    	}
    	
    	CPerDiscount(int BookCount,double BookPrice,double Percent)
    	{
    		m_BookCount = BookCount;
    		m_BookPrice = BookPrice;
    		m_Percent   = Percent;
    	}
    	virtual double GetDiscount()
    	{
    		return m_BookCount*m_BookPrice*m_Percent;
    	}
    };
    //按具体价格折扣
    class CPriceDiscount: public CBookStrategy
    {
    private:
    	int     m_BookCount;
    	double  m_BookPrice;
    	double  m_DiscountPrice;
    public:
    	double GetDiscountPrice()
    	{
    		return m_DiscountPrice;
    	}
    	void SetPercent(double Price)
    	{
    		m_DiscountPrice = Price;
    	}
    	virtual double GetDiscount()
    	{
    		return m_BookCount*m_DiscountPrice;
    	}
    	CPriceDiscount(int BookCount,double BookPrice,double DiscountPrice)
    	{
    		m_BookCount = BookCount;
    		m_BookPrice = BookPrice;
    		m_DiscountPrice   = DiscountPrice;		
    	}
    };
    
    int main(int argc, char* argv[])
    {
    
    	CBookStrategy* pStrategy;
    	//无折扣
    
    	pStrategy = new CNonDiscount(2,35);
    	cout << pStrategy->GetDiscount() << '\n';
    	delete pStrategy;
    	//百分比折扣
    	pStrategy = new CPerDiscount(2,35,0.85);
    	cout << pStrategy->GetDiscount()<< '\n';
    	delete pStrategy;
    	//具体价格折扣
    	pStrategy = new CPriceDiscount(2,35,33);
    	cout <<
    		pStrategy->GetDiscount() << '\n';
    	delete pStrategy;
    
    	return 0;
    }
    
  • 相关阅读:
    浏览器操作本地缓存记录一下
    dotnet new Getting ready... Object reference not set to an instance of an object.
    IIS上vue打包后接口跨域解决
    SpringBoot前言
    Node聊天室和socket.io原理与功能总结
    Node加解密原理和功能探索总结
    Node中文件断点续传原理和方法总结
    Node短链原理与功能实现总结
    Node中F2A原理及功能实现总结
    Node图形邮箱手机验证码实现方法总结
  • 原文地址:https://www.cnblogs.com/lzihua/p/2385048.html
Copyright © 2020-2023  润新知