public class Test { public static void main(String[] args) { if(student is Granduate){ //xxxxxxx }else if if(student is Master){ //xxxxxxx } if(student is Doctor){ //xxxxxxx }
仔细分析,这个问题的可变性代码就是3个算法,可以考虑先把这3个算法分别用三个类封装起来: public class GranduateStipend{ public void Payoff(){//本科生计算算法} } public class MasterStipend{ public void Payoff(){//硕士生计算算法} } public class DoctorStipend{ public void Payoff(){//博士生计算算法} } 根据面向抽象编程的原则,可以把3个算法抽象成一个接口或者一个抽象类,并使这3个算法类成为它的子类。 实际中客户端是面对接口编程,而真正的算法实现却是由抽象接口的子类完成,做到了可变的算法和客户实现隔离。
参与者 Strategy:定义所有支持的算法的公共接口。
Context:用一个ConcreteStrategy对象来配置。 维护一个对Strategy对象的引用。 可定义一个接口来让Stategy访问它的数据。 ConcreteStrategy: 以Strategy接口实现某具体算法。 协作方法: Strategy and Context interact to implement the chosen algorithm A context forwards requests from its clients to its strategy 例如:
public class Context { Strategy stra; public Context(Strategy stra) { this.stra = stra; } public void doMethod() {
stra.method();
} }
public class Test { public static void main(String[] args) { Context ctx = new Context(new StrategyImplA()); ctx.doMethod(); ctx = new Context(new StrategyImp());
ctx.doMethod(); ctx = new Context(new StrategyImplC()); ctx.doMethod(); } }