设计模式之策略模式
参考:https://www.cnblogs.com/java-my-life/archive/2012/05/10/2491891.html
前提:分为三部分(环境、抽象策略类、具体策略类),定义一组算法,并切封装这些算法继承自同一父类并可相互替换。(ps:好久没更新了,不知道更啥,先发着策略模式。。。)
应用场景:如折扣的计算可分离开来。
1 环境类:
public class Context {
//持有一个具体策略的对象
private Strategy strategy;
//传入具体策略对象
public Context(Strategy strategy) {
this.strategy = strategy;
}
String contextHandler(String msg) {
return strategy.handler(msg);
}
}
2 抽象策略类:
public interface Strategy {
String handler(String msg);
}
3 具体策略类:
public class StrategyAImpl {
String handler(String msg) {
return "当前是具体策略A类:" + msg;
}
}
public class StrategyBImpl {
String handler(String msg) {
return "当前是具体策略B类:" + msg;
}
}
4 调用:
public class Test {
public static void main(String[] args) {
Strategy strategyA = new StrategyAImpl("6666");
Context context1 = new Context(strategy);
System.out.println("A算法:"+context1.getHandler()); //结果:“A算法:当前是具体策略A类:666”
Strategy strategyB = new StrategyBImpl("6666");
Context context2 = new Context(strategy);
System.out.println("B算法:"+context2.getHandler()); //结果:“A算法:当前是具体策略A类:666”
}
}
5 结合Java泛型使用策略模式指定类型
//==环境类==================================
public interface OrmHandler<T> {
T handler(ResultSet rs) throws Exception;
}
//==具体策略类1==================================
public class SingletonBeanHandler<T> implements OrmHandler<T> {
private Class<T> clazz;
public SingletonBeanHandler(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public T handler(ResultSet rs) throws Exception {
Object newInstance = clazz.newInstance();
if (rs != null && rs.next()) {
newInstance = OrmUtil.columnToProperty(rs, clazz);
}
return (T) newInstance;
}
}
//==具体策略类2==================================
public class ListBeanHandler<T> implements OrmHandler<List<T>> {
private Class<T> clazz;
public ListBeanHandler(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public List<T> handler(ResultSet rs) throws Exception {
ArrayList<T> arrayList = new ArrayList<>();
if (rs == null)
return arrayList;
while (rs.next()) {
T columnToProperty = OrmUtil.columnToProperty(rs, clazz);
arrayList.add(columnToProperty);
}
return arrayList;
}
}
用法:====================================
new ListBeanHandler<>(UrpUser.class).handler(rs)
new SingletonBeanHandler<>(UrpUser.class).handler(rs);