策略模式
感觉策略模式跟简单工厂模式差不多。
策略模式首先定义一个策略的抽象类,每一个具体的策略都是继承这个抽象类
然后定义一个上下文类,类里面一个策略对象,类里有策略的对应方法,方法体关联策略对象的方法
使用策略的时候就直接调用上下文的方法就好了
package com.factory; public abstract class CashSuper { protected double price; protected int count; public abstract double acceptCash(); } class CashNormal extends CashSuper{ @Override public double acceptCash() { double result=price*count; return result; } public CashNormal(double price,int count){ this.price=price; this.count=count; } } class CashRebate extends CashSuper{ private double moneyRebate; @Override public double acceptCash() { double result=0; result=price*count*moneyRebate; return result; } public CashRebate(double price,int count,double moneyRebate){ this.price=price; this.count=count; this.moneyRebate=moneyRebate; } } class CashReturn extends CashSuper{ private double get; private double back; @Override public double acceptCash() { double result=price*count; int x=(int)(result/get); result=result-x*back; return result; } public CashReturn(double price,int count,double get,double back){ this.price=price; this.count=count; this.get=get; this.back=back; } }
package com.factory; public class CashContext { CashSuper cash; public CashContext(CashSuper cash){ this.cash=cash; } public double acceptCash(){ return cash.acceptCash(); } }
package com.strategy; import java.util.Scanner; public class Test { public static void main(String[] args){ Scanner input=new Scanner(System.in); System.out.println("选择消费策略(A正常、B8折、C满500送100):"); char type=input.next().charAt(0); System.out.println("输入单价、数量:"); double price=input.nextDouble(); int count=input.nextInt(); double result=0; CashContext context=null; switch(type){ case 'A': context=new CashContext(new CashNormal(price,count)); break; case 'B': context=new CashContext(new CashRebate(price, count, 0.8)); break; case 'C': context=new CashContext(new CashReturn(price,count,500,100)); break; default: context=new CashContext(new CashNormal(price,count)); } result=context.acceptCash(); System.out.println("应收"+result); } }
上面仅仅使用的是策略模式,其实达到的效果不是很好,下面和简单工厂模式结合使用下:
package com.strategy; public class CashContext {/*这里使用了一点简单工厂模型*/ CashSuper cash; public CashContext(double price,int count,Character type){ switch(type){ case 'A': cash=new CashNormal(price,count); break; case 'B': cash=new CashRebate(price,count,0.8); break; case 'C': cash=new CashReturn(price,count,500,100); break; default: cash=new CashNormal(price,count); } } public double acceptCash(){ return cash.acceptCash(); } }
package com.strategy; import java.util.Scanner; public class Test { public static void main(String[] args){ Scanner input=new Scanner(System.in); System.out.println("选择消费策略(A正常、B8折、C满500送100):"); char type=input.next().charAt(0); System.out.println("输入单价、数量:"); double price=input.nextDouble(); int count=input.nextInt(); double result=0; CashContext context=new CashContext(price,count,type); result=context.acceptCash(); System.out.println("应收"+result); } }