商场收银软件
如下面这样一个收银界面,如果再加上打折、或者满减、等活动,首先用用简单工厂实现。
现金收费抽象类:
abstract class CashSuper
{
public abstract double acceptCash(double money);
}
正常收费子类:
class CashNormal:CashSuper()
{
public override double acceptCash(double money)
{
return money;
}
}
打折收费子类:
class CashRebate:CashSuper
{
private double moneyRebate = id;
public CashRebate(string moneyRebate)
{
this.moneyRebate = double.Parse(moneyRebate);
}
public override double acceptCash(double money)
{
return money * moneyRebate;
}
}
返利收费子类:
class Cashreturn:cashSuper
{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(string moneyCondition,string moneyReturn)
{
this.moneyCondition = double.Parse(moneyCondition);
this.moneyReturn = double.Parse(moneyReturn);
}
public override double acceptCash(double money)
{
double return = money;
if(money >= moneyCondition)
result = money - Math.Floor(money / moneyCondition) * moneyReturn;
return result;
}
}
现金收费工厂:
class CashFactory
{
public static CashSuper createCashAccept(string type)
{
CashSuper cs = null;
swith(type)
{
case "正常收费":
cs = new CashNormal();
break;
case "满300返100":
CashReturn cr1 = new CashReturn("300","100");
cs = cr1;
break;
case "打8折":
CashRebate cr2 = new CashReturn("0.8");
cs = cr1;
break;
}
return cs;
}
}
客户端主程序(主要部分):
double total = 0.0d;
private void btn0k_Click(object sender,EventArgs e)
{
CashSuper csuper = CashFoctory.createCashAccept(cbxType,SelectedItem.ToString());
double totalPrices = 0d;
totalPrices = csuper.acceptCash(Convert.ToDouble(txtPrice,Text)
* Convert.ToDouble(txtNum.Text));
total = total + totalPrices;
lbxList.Item.Add("单价:" + textPrice.Text + "数量:" + txtNum.Text + " "
+ cbxType.SelectedItem + "合计:" + totalPrice,ToStirng());
lblResult.Text = total.ToString();
}
面向对象的编程,并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,是具有相同属性和功能的对象的抽象集合才是类。
但是这样的写法有没有局限呢?如果再加上另一种促销手段呢,比如,需要满100积分10点,以后要领取奖品又该如何呢?每次维护和扩展收费方式都要改动这个工厂,以致代码需要重新编译部署……所以接下来我会继续完善用策略方法的编写模式。