1、策略类:
package com.hhdys.opertion;
/**
* Created by zhangkai on 16/5/29.
*/
public abstract class CashSuper {
public abstract void total();
}
2、正常收费算法类:
package com.hhdys.opertion;
/**
* Created by zhangkai on 16/5/29.
*/
public class CashNormal extends CashSuper {
@Override
public void total() {
System.out.println("正常收费!!!");
}
}
3、打折收费算法类:
package com.hhdys.opertion;
/**
* Created by zhangkai on 16/5/29.
*/
public class CashRebate extends CashSuper {
@Override
public void total() {
System.out.println("打折收费!!!");
}
}
4、满减收费算法类:
package com.hhdys.opertion;
/**
* Created by zhangkai on 16/5/29.
*/
public class CashReturn extends CashSuper {
@Override
public void total() {
System.out.println("满减收费!!!");
}
}
5、上下文类:维护策略对象的引用
package com.hhdys.context;
import com.hhdys.opertion.CashSuper;
/**
* Created by zhangkai on 16/5/29.
*/
public class CashContext {
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper) {
this.cashSuper = cashSuper;
}
public void total(){
cashSuper.total();
}
}
6、主方法:
package com.hhdys.main;
import com.hhdys.context.CashContext;
import com.hhdys.opertion.CashNormal;
import com.hhdys.opertion.CashRebate;
import com.hhdys.opertion.CashReturn;
/**
* Created by zhangkai on 16/5/29.
*/
public class StrategyMain {
public static void main(String[] args){
System.out.println("策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,\n此模式让算法的变化,不会影响用到算法的客户。");
CashContext context=new CashContext(new CashNormal());
context.total();
context=new CashContext(new CashRebate());
context.total();
context=new CashContext(new CashReturn());
context.total();
}
}
7、运行结果:
策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,
此模式让算法的变化,不会影响用到算法的客户。
正常收费!!!
打折收费!!!
满减收费!!!