策略模式:封装变化,封装算法
package com.jiangwg.psj.design;
import java.util.Scanner;
/**
* @Auther: Peng Senjie
* @Date: 2018-09-14
* @Description: 策略模式
*/
public class Celue {
public static double total =0.0;//总价
public static double price =0.0;//单价
public static int num =0;//数量
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("请输入单价:");
String s = scanner.nextLine();
System.out.println("请输入数量:");
String s1 = scanner.nextLine();
System.out.println("请输入折扣方式:1、不打折,2、7折,3、满100返30");
String rebate = scanner.nextLine();
price = Double.parseDouble(s);
num = Integer.parseInt(s1);
//问题:出现活动打折或者其他情况,代码不够灵活,可以加输入框,如果增加满减活动,利用简单工厂,不断写打折子类。。
//total = one(price,num);
//简单工厂:将共性属性抽取出来,abstract
//two(price,num,rebate);
//简单工厂(工厂生产算法)能实现这个需求,但是对于一些算法时常变动的,每次都需要修改工厂,十分糟糕,--》策略模式:算法也是一种策略,随时
//可以相互替换,这是变化点,我们需要封装变化点,着十分重要,简单工厂需要认识两个类,策略只需要一个类,降低耦合
three(price,num,rebate);
System.out.println("总价:"+total);
}
private static double one(double v,double v1){
total=v*v1;
System.out.println(total);
return total;
}
private static double two(double v,double v1,String rebate){
CashSuper accept = CashFactory.createAccept(rebate);
total = accept.acceptCash(v * v1);
return total;
}
private static double three(double v,double v1,String rebate){
CashContext cashContext = new CashContext(rebate);
total = cashContext.GetResult(v * v1);
return total;
}
}
abstract class CashSuper{
public abstract double acceptCash(double money);
}
class CashNormal extends CashSuper{
//正常类
@Override
public double acceptCash(double money) {
return money;
}
}
class CashRebate extends CashSuper{
//打折,
private double rebate=1;
public CashRebate(double rebate){
this.rebate=rebate;
}
@Override
public double acceptCash(double money) {
return money*rebate;
}
}
class CashReturn extends CashSuper{
//返利
private double moneyCon=0;
private double moneyRet=0;
public CashReturn(String moneyCon,String moneyRet) {
this.moneyCon=Double.parseDouble(moneyCon);
this.moneyRet=Double.parseDouble(moneyRet);
}
@Override
public double acceptCash(double money) {
double result=money;
if(money>moneyCon){
result=money-moneyRet;
}
return result;
}
}
class CashFactory{
public static CashSuper createAccept(String type){
CashSuper cashSuper=null;
switch (type){
case "1":
cashSuper=new CashNormal();
break;
case "2":
cashSuper=new CashRebate(0.7);
break;
case "3":
cashSuper=new CashReturn("100","30");
break;
}
return cashSuper;
}
}
class CashContext {
CashSuper cashSuper=null;
public CashContext(String type){
switch (type){
case "1":
cashSuper=new CashNormal();
break;
case "2":
cashSuper=new CashRebate(0.7);
break;
case "3":
cashSuper=new CashReturn("100","30");
break;
}
}
public double GetResult(double money){
return cashSuper.acceptCash(money);
}
}