定义
策略模式,就是将一个算法的不同实现封装成一个个单独的类,这些类实现同一个接口,使用者直接使用该接口来访问具体的算法
java 编程思想
package chapter9interfaces.classprocessor;
import java.util.Arrays;
class Processor {
public String name() {
return getClass().getSimpleName();
}
Object process(Object input) {
return input;
}
}
class Upcase extends Processor {
String process(Object input) { //返回协变类型
return ((String) input).toUpperCase();
}
}
class Downcase extends Processor {
String process(Object input) {
return ((String) input).toLowerCase();
}
}
class Splitter extends Processor {
String process(Object input) {
return Arrays.toString(((String) input).split(" "));
}
}
public class Apply {
public static void process(Processor p, Object s) { //策略设计模式 根据所传递的参数对象的不同,而具有不同行为的方法
System.out.println("Using Processor " + p.name()); // 方法中包含算法中固定不变的部分 ,策略就是传递进入的参数对象,包含变化的部分,包含要执行的代码
System.out.println(p.process(s));
}
public static String s = "Disagreement with beliefs is by definition incorrect";
public static void main(String[] args) {
process(new Upcase(), s);
process(new Downcase(), s);
process(new Splitter(), s);
}
}
https://blog.csdn.net/chenjie19891104/article/details/6396458
package chapter9interfaces.strategy;
// 公共方法回调用类
interface SomeCallBack {
public void doTheSame();
}
// 策略类
interface Strategy {
void execute(SomeCallBack scb);
}
// 策略实现类
class ConcreteStrategy1 implements Strategy {
@Override
public void execute(SomeCallBack scb) {
scb.doTheSame();
System.out.println(getClass().getSimpleName());
}
}
class ConcreteStrategy2 implements Strategy {
@Override
public void execute(SomeCallBack scb) {
scb.doTheSame();
System.out.println(getClass().getSimpleName());
}
}
class ConcreteStrategy3 implements Strategy {
@Override
public void execute(SomeCallBack scb) {
scb.doTheSame();
System.out.println(getClass().getSimpleName());
}
}
public class Context {
public static void main(String[] args) {
Strategy strategy = new ConcreteStrategy1();
SomeCallBack scb = new SomeCallBack() {
@Override
public void doTheSame() {
System.out.println("do the same");
}
};
strategy.execute(scb);
strategy = new ConcreteStrategy2();
strategy.execute(scb);
}
}