import java.util.Scanner;
// 不同算法封装成不同的类 策略模式
abstract class CashSuper
{
public abstract double acceptCash(double money);
}
class CashNormal extends CashSuper
{
public double acceptCash(double money)
{
return money;
}
}
class CashReturn extends CashSuper
{
private double moneyCondition = 0.0;
private double moneyReturn = 0.0;
public CashReturn(String moneyCondition,String monyeReturn)
{
this.moneyCondition = Integer.parseInt(moneyCondition);
this.moneyReturn = Integer.parseInt(monyeReturn);
}
public double acceptCash(double money)
{
double result = money;
if(money>=moneyCondition)
{
result = money - (money/moneyCondition)*moneyReturn;
}
return result;
}
}
class CashRebate extends CashSuper
{
private double discount = 0.0;
public CashRebate(String discount)
{
this.discount = Integer.parseInt(discount);
}
public double acceptCash(double money)
{
money = money * discount*0.1;
return money;
}
}
class CashContext
{
CashSuper cs = null;
public CashContext(String type)
{
if(type.equals("正常收费")){
CashNormal cs0 = new CashNormal();
cs = cs0;
}
if(type.equals("300"))
{
CashReturn cr1 = new CashReturn("300","100");
cs = cr1;
}
if(type.equals("打折"))
{
CashRebate cr2 = new CashRebate("8");
cs = cr2;
}
}
public double GetResult(double money)
{
return cs.acceptCash(money);
}
}
public class strategy {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String s = sc.next();
while(!s.equals("q"))
{
double price = 600;
CashContext cc = new CashContext(s);//根据不同输入创建不同需要:工厂模式
double total = 0;
total = cc.GetResult(price);
System.out.println("原价"+price+"元");
System.out.println("现在"+total+"元");
s = sc.next();
}
}
}
策略模式
最新推荐文章于 2024-08-28 11:33:13 发布