//20210124
写在前面:刚期末考试完,考了面向对象,里边儿有23个设计模式,我寻思着考完挨个儿实现一下,本文实现策略模式
策略模式核心思想
- 设置一个算法父类,然后实现多种不同方法子类,用户只用选择背景,以及背景中的算法,就可以实现不同功能
程序源代码:
/**
* 活动父类
*/
public abstract class CashSuper{
public abstract double acceptCash(double money);
}
/**
* 返利类型
*/
public class CashReturn extends CashSuper{
private double moneyConditation = 0.0;//返利条件
private double moneyReturn = 0.0d;//返利数额
public CashReturn(double moneyConditation,double moneyRebate){
this.moneyConditation = moneyConditation;
this.moneyReturn = moneyRebate;
}
@Override
public double acceptCash(double money){
double result = money;
if(money >= moneyConditation){
result = money - Math.floor(money/moneyConditation)*moneyReturn;
}
return result;
}
}
/**
* 打折,传入折扣数,返回打折后价钱(默认不打折)
*/
public class CashRebate extends CashSuper{
private double moneyRebate = 1;//折扣
public CashRebate (double moneyRebate){
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money){
return money*moneyRebate;
}
}
/**
* 普通模式,没有任何打折活动
*/
public class CashNormal extends CashSuper{
@Override
public double acceptCash(double money){
return money;
}
}
/**
* 背景,用于承载算法
*/
public class CashContext{
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper){
this.cashSuper = cashSuper;
}
public double getResult(double money){
return cashSuper.acceptCash(money);
}
}
/**
* 测试主类
*/
import java.util.Scanner;
public class Main{
public static void main(String args[]){
CashContext cashContext = null;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入折扣方法:1、2、3");
System.out.println("1.无活动(原价)、2.满300减100、3.打八折");
int in = scanner.nextInt();
String type = "";
//选择折扣类型
switch(in){
case 1:
cashContext = new CashContext (new CashNormal());
type += "无活动(原价)";
break;
case 2:
cashContext = new CashContext(new CashReturn(300,100));
type += "满300减100";
break;
case 3:
cashContext = new CashContext(new CashRebate(0.8));
type += "打八折";
break;
default:
System.out.println("请输入1/2/3其中的一个数字");
return;
}
double totalPrices = 0;
System.out.println("单件价格:");
double price = scanner.nextDouble();
System.out.println("总数量:");
double num = scanner.nextDouble();
totalPrices = cashContext.getResult(price * num);
System.out.println("单价:" + price + ",数量" + num + ",折扣类型" + type + ",总价" + totalPrices);
scanner.close();
}
}
- 输出如下:
以上
希望对大家有所帮助