模式結(jié)構(gòu)
抽象策略(Strategy):由接口或者抽象類實現(xiàn),抽象出具體策略需要的接口
具體策略(ConcreteStrategy):包裝了具體的邏輯
環(huán)境(Context)角色:持有一個Strategy的引用梨与,判斷使用哪種策略
步驟1
以去KFC為例乌助,先實現(xiàn)了套餐(抽象策略)
public interface Meal {
/**
* 套餐類型
*/
void mealType();
}
步驟2
這里單人套餐和雙人套餐都是(具體策略)
public class OneMeal implements Meal{
@Override
public void mealType() {
System.out.println("單人套餐:雞腿堡+中可");
}
}
public class TwoMeal implements Meal{
@Override
public void mealType() {
System.out.println("雙人套餐:奧爾良雞腿堡+雞肉卷+2杯中可");
}
}
步驟3
實現(xiàn)了一個營業(yè)員(環(huán)境)趁桃,持有了抽象策略引用
public class SalesMan {
private Meal meal;
public void sale(int num) {
if(num == 1) {
meal = new OneMeal();
}else if(num == 2){
meal = new TwoMeal();
}
}
public void recommend() {
meal.mealType();
}
}
步驟4
測試死姚,店里來了2人苛蒲,然后營業(yè)員推薦了雙人套餐
SalesMan salesMan = new SalesMan();
salesMan.sale(2);
salesMan.recommend();