策略模式是我在編程學習中學到的第三個設計模式 在此用我自己的理解結合網(wǎng)上的教程概括一下設計模式.
策略模式的用途
- 如果在一個系統(tǒng)里面有許多類顷歌,它們之間的區(qū)別僅在于它們的行為,那么使用策略模式可以動態(tài)地讓一個對象在許多行為中選擇一種行為泛鸟。
- 一個系統(tǒng)需要動態(tài)地在幾種算法中選擇一種绎签。
- 如果一個對象有很多的行為勒奇,如果不用恰當?shù)哪J剿κ@些行為就只好使用多重的條件選擇語句來實現(xiàn)。
策略模式的核心
用模板將所有策略封裝起來 降低系統(tǒng)耦合度
枚舉策略
public enum AnnualFee {
VIP5("vip5") {
@Override
public int amount(int year) {
// TODO Auto-generated method stub
return year*80;
}
},VIP4("vip4") {
@Override
public int amount(int year) {
// TODO Auto-generated method stub
return year*85;
}
},VIP3("vip3") {
@Override
public int amount(int year) {
// TODO Auto-generated method stub
return year*90;
}
},VIP2("vip2") {
@Override
public int amount(int year) {
// TODO Auto-generated method stub
return year*95;
}
},VIP1("vip1") {
@Override
public int amount(int year) {
// TODO Auto-generated method stub
return year*100;
}
};
private String rights;
public abstract int amount(int year);
private AnnualFee(String rights) {
this.rights = rights;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
}
這是我在學習策略模式的時候寫的一個年費策略 根據(jù)不同vip等級 傳入未付費的年數(shù) 得到需要付費的金額
double amount = AnnualFee.valueOf(rights).amount(year);
枚舉策略需要的context就是枚舉類本身 而重寫的每個amount方法就是具體的strategy
當然 也引出了其他問題 如果我事先不知道我的vip等級 我就少不了一大堆冗長的if-elseif語句(這里用了enum.valueOf,當時沒想到用工廠模式)而這是也是策略模式的缺點,通常策略模式不單獨出現(xiàn),要配合其他設計模式一起使用