我来给个实例
//A策略
public class Astragety implements Istragety{
public String doSomething(String ori) {
return ori+"AA";
}
}
//B策略
public class Bstragety implements Istragety{
public String doSomething(String ori) {
return ori+"BB";
}
}
//策略接口
public interface Istragety {
public String doSomething(String ori);
}
//使用策略的上下文
public class StragetyContext {
private Istragety istragety;
public void setIstragety(Istragety istragety) {
this.istragety = istragety;
}
public void doWhatUWant(){
System.out.println(istragety.doSomething("what u want:"));
}
}
//开始使用吧~~~~~
public class Stragety {
public static void main(String[] args) {
StragetyContext stragetyContext = new StragetyContext();
stragetyContext.setIstragety(new Astragety());
stragetyContext.doWhatUWant();
stragetyContext.setIstragety(new Bstragety());
stragetyContext.doWhatUWant();
}
}
回复 更多评论