策略模式

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();
		}
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值