本文内容参考自《大话设计模式》(程杰 著)
注:以下代码为java实现
版本1
需求:
做一个商场收银软件,营业员根据客户所购买商品的单价和数量,向客户收费。
关键代码:
public class Cash
{
private double total = 0;
public void submit(int num, double price)
{
double totalPrices = num * price;
total += totalPrices;
System.out.println("单价:" + price + " 数量:" + num + "合计:" + totalPrices);
}
public double getTotal()
{
return total;
}
public void setTotal(double total)
{
this.total = total;
}
}
版本2
需求:
增加打折功能
思路1:修改代码,比如打7折,则total *= 0.7;
评价:如果取消打折,或者修改折扣,需要频繁修改代码,不推荐。
思路2:增加折扣选项,关键代码如下:
public class Cash
{
private double total = 0;
private int selectedIndex = 0;
public void selectFormLoad()
{
String[] selectForm = { "正常收费", "打8折", "打7折", "打5折" };
selectedIndex = 0;
}
public void submit(int num, double price)
{
double totalPrices = 0;
switch (selectedIndex)
{
case 0:
totalPrices = num * price;
break;
case 1:
totalPrices = num * price * 0.8;
break;
case 2:
totalPrices = num * price * 0.7;
break;
case 3:
totalPrices = num * price * 0.5;
break;
}
total += totalPrices;
System.out.println("单价:" + price + " 数量:" + num + "合计:" + totalPrices);
}
public double getTotal()
{
return total;
}
public void setTotal(double total)
{
this.total = total;
}
public int getSelectedIndex()
{
re