定义了算法家族, 分别封装起来, 让它们之间可以互相替换.
//举例,假设有多个锦囊,没个锦囊中有不同的计谋
/**
* 计谋接口
* @author fan
*
*/
public interface Scheme {
public String execute();
}
/**
* 绿色计谋
* @author fan
*
*/
public class GreenSilk implements Scheme{
@Override
public String execute() {
// TODO Auto-generated method stub
return "run away";
}
}
/**
* 红色计谋
* @author fan
*
*/
public class RedSilk implements Scheme{
@Override
public String execute() {
// TODO Auto-generated method stub
return "kill";
}
}
/**
* 计谋持有者 锦囊
* @author fan
*
*/
public class SilkBox {
private Scheme scheme;
public SilkBox(Scheme scheme){
this.scheme=scheme;
}
public String execute() {
// TODO Auto-generated method stub
return this.scheme.execute();
}
}
//测试下
public class Test {
public static void main(String[] args) {
SilkBox box = new SilkBox(new GreenSilk());
System.out.println(box.execute());
box = new SilkBox(new RedSilk());
System.out.println(box.execute());
}
}
//输出
run away
kill