策略模式主要是为了封装变化,体现在Context类中.
策略模式+工厂模式(如下Context类),可以更好的隔离客户端.(减少了耦合嘛)
策略模式解析
策略模式是定义一系列算法的方法,从概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合.
1 2 3 4 5 6 7 8 9
| package strategy;
public abstract class Strategy {
public abstract double acceptCash(double money); }
|
1 2 3 4 5 6 7 8 9 10 11
| package strategy;
public class Normal extends Strategy {
public double acceptCash(double money) { return money; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| package strategy;
public class Rate extends Strategy { private double rate = 0.9;
public double acceptCash(double money) { return rate * money; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package strategy;
public class Context { private Strategy strategy;
public Context(Type type) { switch (type) { case NORMAL: strategy = new Normal(); break; case RATE: strategy = new Rate(); break; } }
public double getResult(double money) { return strategy.acceptCash(money); }
enum Type {NORMAL, RATE, RETURN} }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package strategy;
public class Main { public static void main(String[] args) { Context context = null; context = new Context(Context.Type.NORMAL); double accept = context.getResult(100); System.out.println(accept);
context = new Context(Context.Type.RATE); accept = context.getResult(100); System.out.println(accept); } }
|