一、抽象策略类
package com.example.study.strategy;
public interface IColor {
void describe(ResultCallback callback);
String argb();
interface ResultCallback {
void result(String msg);
}
}
二、具体策略类
package com.example.study.strategy;
public class Blue implements IColor {
@Override
public void describe(ResultCallback callback) {
callback.result("0xFF0000FF");
System.out.println("this is blue");
}
@Override
public String argb() {
return "blue";
}
}
package com.example.study.strategy;
public class Red implements IColor {
@Override
public void describe(ResultCallback callback) {
callback.result("0xFFFF0000");
System.out.println("this is red");
}
@Override
public String argb() {
return "red";
}
}
package com.example.study.strategy;
public class Yellow implements IColor {
@Override
public void describe(ResultCallback callback) {
callback.result("0xFFFFFF00");
System.out.println("this is yellow");
}
@Override
public String argb() {
return "yellow";
}
}
三、策略Context,获取具体策略实例
package com.example.study.strategy;
import java.util.HashMap;
import java.util.Map;
public class ColorContext {
private IColor color;
private static Map<String, String> map = new HashMap<String, String>() {{
put("blue", "com.example.study.strategy.Blue");
put("red", "com.example.study.strategy.Red");
put("yellow", "com.example.study.strategy.Yellow");
}};
private static IColor getColor(String type) {
IColor color = null;
try {
try {
color = (IColor) Class.forName(map.get(type)).newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return color;
}
public void setColor(String type) {
this.color = getColor(type);
}
public void describe(IColor.ResultCallback callback) {
this.color.describe(callback);
}
public String argb() {
return this.color.argb();
}
}
四、测试调用
package com.example.study;
import com.example.study.strategy.ColorContext;
public class MyClass {
public static void main(String[] args) {
ColorContext context = new ColorContext();
context.setColor("red");
context.describe(System.out::println);
context.setColor("yellow");
System.out.println(context.argb());
}
}