天天看點

政策模式

場景:當不同條件調用不同的算法或者政策時。

優點:1.可以減少大量的if else,減少耦合度。

           2.友善擴充和維護

缺點:1.類的數量變多,機構變複雜了。

           2.向外暴露了政策

類圖:

政策模式

代碼:

政策接口

1. public interface Strategy {
2. public void method();
3. }      

政策實作

1. public class StrategyA implements Strategy {
2. @Override
3. public void methodA() {
4. System.out.println("方法A");
5.     }
6. }      
1. public class StrategyB implements Strategy {
2. @Override
3. public void methodB() {
4. System.out.println("方法B");
5.     }
6. }      
1. public class StrategyC implements Strategy {
2. @Override
3. public void methodC() {
4. System.out.println("方法C");
5.     }
6. }      

上下文角色

1. public class Context {
2. //抽象政策
3. private Strategy strategy = null;
4. //構造函數設定具體政策
5. public Context(Strategy strategy) {
6. this.strategy = strategy;
7. }
8. public void setContext(Strategy strategy) {
9. this.strategy = strategy;
10. }
11. //封裝後的政策方法
12. public void doMethod() {
13. this.strategy.method();
14. }
15. }      

調用(如果為了美化 可以将這個類設計為工廠 這樣可以保持對入口的統一管理)

1. public class Client {
2. public static void main(String[] args) {
3. //聲明上下文對象
4. Context context = new Context();
5. context.setContext(new StrategyA());
6. //執行封裝後的方法
7. context.method();
8. context.setContext(new StrategyB());
9. //執行封裝後的方法
10. context.method();
11. }
12. }      

繼續閱讀