策略模式 商品促銷

2021-07-22 14:56:16 字數 2074 閱讀 9155

許多商家為了提高知名度或是其他原因會進行商品**活動。而有時對於新老客戶的**策略又有所不同。比如新客戶打9折,老客戶打8折。(當然,這只是比喻)我們可以用簡單的程式來表示這種**活動。

public

class merchandise

//根據型別計算商品**

public

float

calculateprice(int customer, float price) else

if (customer == old_customer)

return price;

}//計算新客戶**

public

float

newcustomerprice(float price)

//計算老客戶**

public

float

oldcustomerprice(float price)

}

乙個簡單的程式就出來了:

81.0

72.0

但是,這卻隱藏著乙個問題,假設現在老闆說有一種特殊的客戶,可以打5折。現在要修改程式,就需要新增多乙個if判斷了:

public

float

caculateprice(int customer, float price) else

if (customer == old_customer) else

if (customer == special_customer)

return price;

}

會發現,如果老闆說又多了一種客戶,就會在程式中多出現乙個if else語句,導致程式顯得越來越臃腫。既然對於每種客戶都採取不同的策略,那麼接下來用策略模式來解決上述問題。

uml圖:

context:操縱策略的環境

strategy:策略的抽象

concretestragety:策略的具體實現

按照圖示,可以嘗試先定義乙個介面,用來計算**:

//計算**的介面,對應strategy

public

inte***ce

caculatestrategy

分別有新老,特殊三種客戶,並且都實現了計算**的介面:

//新客戶**策略,對應concretestrategya

public

class

newcustomer

implements

caculatestrategy

}//老客戶**策略,對應concretestrategyb

public

class

oldcustomer

implements

caculatestrategy

}

有了客戶,最後需要乙個**計算器:

//**計算,對應context

public

class pricecalculator

public

void

setstrategy(caculatestrategy strategy)

public

float

calculateprice(float price)

}

結果:

老客戶:72.0

用上述方式,如果要新增乙個特殊客戶,就會顯得輕便許多,省去了if else的臃腫邏輯:

public

class

specialcustomer

implements

caculatestrategy

}

缺點

二 商品促銷 策略模式

現金收費抽象類 package ch02strategy abstract class cashsuper 正常收費子類 package ch02strategy public class cashnormal extends cashsuper 打折收費子類 package ch02strateg...

策略模式 商場促銷

封裝的簡單策略類 ifndef stratege h define stratege h include using namespace std class stratege class concretestrategea public stratege class concretestratege...

商場促銷 策略模式(設計模式)

商場收銀時,如何 用打折還是返利,其實都是一些演算法,用工廠來生成演算法物件,這沒有錯,但演算法本身只是一種策略,最重要的是這些演算法是隨時都可能互相替換的,就這點變化,而封裝變化點是我們物件導向的一種很重要的思維方式。來看看策略模式的結構圖和基本 策略模式 strategy 定義了演算法家族,分別...