java設計模式(六)策略模式
阿新 • • 發佈:2017-07-19
() pan win with blog trac java設計模式 ring ide
策略模式定義了一系列的算法,並將每一個算法封裝起來,而且使它們可以相互替換,讓算法獨立於使用它的客戶而獨立變化,具體應用場景如第三方支付對接不同銀行的算法。
要點:1)抽象策略角色
2)具體策略角色:包裝相關算法和行為
3)環境角色:持有一個策略類的引用,最終給客戶端調用
1、抽象策略接口
public interface SwimmingStratege { public void swimming(); }
2、具體策略角色SwimmingWithFoot
public class SwimmingWithFoot implements SwimmingStratege {public void swimming() { System.out.println("我借助腳滑動在水中遊走"); } }
3、具體策略角色SwimmingWithWind
public class SwimmingWithWind implements SwimmingStratege { public void swimming() { System.out.println("我借助風在水中遊走"); } }
4、環境角色Duck 抽象類
public abstract class Duck { public voidquack() { System.out.println("嘎嘎嘎"); } public abstract void display(); private SwimmingStratege swimmingStratege; public void setSwimmingStratege(SwimmingStratege swimmingStratege) { this.swimmingStratege = swimmingStratege; } public void swimming() { swimmingStratege.swimming(); } }
5、環境角色RealDuck
public class RealDuck extends Duck { public RealDuck() { super(); super.setSwimmingStratege(new SwimmingWithFoot()); } @Override public void quack() { super.quack(); } public void display() { System.out.println("我是真的鴨子"); } }
6、環境角色
public class YellowDuck extends Duck { public YellowDuck() { super(); super.setSwimmingStratege(new SwimmingWithWind()); } @Override public void quack() { super.quack(); } public void display() { System.out.println("我是大黃鴨"); } }
7、測試
public class Model { public static void main(String[] args) { Duck duck = new RealDuck(); // Duck duck = new YellowDuck(); duck.display(); duck.quack(); duck.swimming(); } }
java設計模式(六)策略模式