[b][size=medium]strategy定义[/size][/b]
Strategy 是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类.
这里以字符串格式化为例子:
[img]http://dl.iteye.com/upload/attachment/0072/4102/2ad71da3-2a69-364c-bc93-3b54a8f5d0f9.jpg[/img]
使用Strategy 模式可以在用户需要变化时,修改量很少,而且快速.
[img]http://dl.iteye.com/upload/attachment/0072/4104/cc261a4e-d92d-3987-9229-61211d1f8046.jpg[/img]
Strategy 是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类.
这里以字符串格式化为例子:
package strategy;
//算法接口类,声明通用的方法
public interface Replace {
public String replace(String s);
}
package strategy;
//算法类A,实现接口的方法
public class ReplaceA implements Replace {
public String replace(String s) {
// TODO Auto-generated method stub
return s.toLowerCase();
}
}
package strategy;
//算法类B,实现接口的方法
public class ReplaceB implements Replace {
public String replace(String s) {
return s.toUpperCase();
}
}
package strategy;
//策略管理类,指定使用策略,操作指定策略的算法
public class Context {
private Replace replace;
public Replace getReplace() {
return replace;
}
public void setReplace(Replace replace) {
this.replace = replace;
}
public String format(String s){
return replace.replace(s);
}
}
package strategy;
//测试类
public class Test {
public static void main(String[] args) {
Replace a = new ReplaceA();
Replace b = new ReplaceB();
Context c = new Context();
//使用过程中,动态的更改策略算法,为策略的更改提供方便,客户端选择算法更容易
c.setReplace(a);
System.out.println(c.format("abcdEFG"));
c.setReplace(b);
System.out.println(c.format("abcdEFG"));
}
}
[img]http://dl.iteye.com/upload/attachment/0072/4102/2ad71da3-2a69-364c-bc93-3b54a8f5d0f9.jpg[/img]
使用Strategy 模式可以在用户需要变化时,修改量很少,而且快速.
[img]http://dl.iteye.com/upload/attachment/0072/4104/cc261a4e-d92d-3987-9229-61211d1f8046.jpg[/img]