策略模式

策略模式  其實很簡單,說得更簡單點就是  java特性的 動態綁定,不多時,貼上code你一看就明白

實現寫一個IStrategy接口,一個operate方法

 

public interface IStrategy {

public void operate();

}

其實3個該接口的實現類:

 

public class OneStrategy implements IStrategy {

@Override

public void operate() {

System.out.println("one");

}

}

 

public class TwoStrategy implements IStrategy {

@Override

public void operate() {

// TODO Auto-generated method stub

System.out.println("TWO");

 

}

}

public class ThreeStrategy implements IStrategy {
@Override
public void operate() {
// TODO Auto-generated method stub
System.out.println("Three");
}
 
}
以上3個類 均實現類 IStrategy接口,並在operate方法內有不同的操作
最後一個Context類  該類用於管理實現IStrategy接口的類
public class Context {
private IStrategy iStrategy;
 
public Context(IStrategy iStrategy) {
this.iStrategy = iStrategy;
}
 
public void operate() {
this.iStrategy.operate();
}
 
public static void main(String[] args) {
Context cxt = new Context(new ThreeStrategy());
cxt.operate();
}
}
這樣  但我們每次創建是IStrategy接口不同的類的時候,會執行你創建的那個類的方法,實現代碼的複用性
 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章