策略模式

壹頁書發表於2017-03-21



這個倒是看著不復雜



策略模式應用
Java.util.Collections#sort(List list, Comparator < ? super T > c)
java.util.Arrays#sort(T[], Comparator < ? super T > c)
HashMap中對hashcode的計算
  1. class Context {  
  2.     // 持有一個具體策略的物件  
  3.     private Strategy strategy;  
  4.   
  5.     /** 
  6.      * 建構函式,傳入一個具體策略物件 
  7.      *  
  8.      * @param strategy 
  9.      *            具體策略物件 
  10.      */  
  11.     public Context(Strategy strategy) {  
  12.         this.strategy = strategy;  
  13.     }  
  14.   
  15.     /** 
  16.      * 策略方法 
  17.      */  
  18.     public void contextInterface() {  
  19.   
  20.         strategy.strategyInterface();  
  21.     }  
  22.   
  23. }  
  24.   
  25. interface Strategy {  
  26.     /** 
  27.      * 策略方法 
  28.      */  
  29.     public void strategyInterface();  
  30. }  
  31.   
  32. class ConcreteStrategyA implements Strategy {  
  33.   
  34.     @Override  
  35.     public void strategyInterface() {  
  36.         // 相關的業務  
  37.     }  
  38.   
  39. }  
  40.   
  41. class ConcreteStrategyB implements Strategy {  
  42.   
  43.     @Override  
  44.     public void strategyInterface() {  
  45.         // 相關的業務  
  46.     }  
  47.   

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2135735/,如需轉載,請註明出處,否則將追究法律責任。

相關文章