大话设计-简单工厂
记录大话设计模式学习,大话设计模式pdf分享:链接:https://pan.baidu.com/s/11h9x-4RffXydf3GFH5_y7g 提取码:x5c3
实现简单计算器的加减乘除运算,做到可维护、可扩展、可复用、且灵活。
可维护举例:业务人员要求加法功能只允许绝对值相加,这时修改代码的区域应只有加法,附近没有其他运算,避免不小心改到了别的运算。
可扩展举例:加个开平方根运算,添加代码的区域附近没有其他运算。
这个简单工厂用于返回运算的实例、每当有新的运算加入,工厂里的switch分支也要添加。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { var operation = OperationFactory.GetOperation("+"); operation.NumberA = Convert.ToDouble(Console.ReadLine()); operation.NumberB = Convert.ToDouble(Console.ReadLine()); Console.WriteLine(operation.GetResult()); Console.ReadLine(); } } //运算基类 public class Operation { private double numberA; public double NumberA { get { return numberA; } set { numberA = value; } } private double numberB; public double NumberB { get { return numberB; } set { numberB = value; } } public virtual double GetResult() { double result = 0; return result; } } public class OperationAdd : Operation { public override double GetResult() { return NumberA + NumberB; } } public class OperationSub : Operation { public override double GetResult() { return NumberA - NumberB; } } public class OperationMul : Operation { public override double GetResult() { return NumberA * NumberB; } } public class OperationDiv : Operation { public override double GetResult() { if (NumberB == 0) { throw new DivideByZeroException(); } return NumberA / NumberB; } } // 简单工厂 public class OperationFactory { public static Operation GetOperation(string operation) { switch (operation) { case "+":return new OperationAdd(); case "-":return new OperationSub(); case "*":return new OperationMul(); case "/":return new OperationDiv(); default:return new Operation(); } } } }
超市结账优惠,打折或满减。
using System; namespace ConsoleApp4 { class Program { public static void Main(string[] args) { var cashSuper = CashFactory.CreateCashSuper("8折"); cashSuper.AcceptCash(900d); } } public abstract class CashSuper { public abstract double AcceptCash(double money); } public class CashNormal : CashSuper { public override double AcceptCash(double money) { return money; } } public class CashRebate : CashSuper { private double rebate; public CashRebate(double rebate) { this.rebate = rebate; } public override double AcceptCash(double money) { return money * rebate; } } public class CashReturn : CashSuper { private double moneyCondition; private double moneyReturn; public CashReturn(double condition,double @return) { moneyCondition = condition; moneyReturn = @return; } public override double AcceptCash(double money) { if (money >= moneyCondition) { return money - ((money / moneyCondition) * moneyReturn); } else { return money; } } } public class CashFactory { public static CashSuper CreateCashSuper(string type) { switch (type) { case "满300减50":return new CashReturn(300d, 50d); case "8折":return new CashRebate(0.8d); default:return new CashNormal(); } } } }
量变会引起质变。