策略模式
收银软件
面向对象的编程,并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,具有相同属性和功能的对象是抽象集合才是类
简单工厂实现
1.抽象打折类
public abstract class CashSuper
{
/// <summary>
/// 收费
/// </summary>
public abstract void AcceptCash();
}
2.创建打折实类
返利收费
public class CashReturn : CashSuper
{
public override void AcceptCash()
{
Debug.Log("返利收费");
}
}
普通收费
public class CashNormal : CashSuper
{
public override void AcceptCash()
{
Debug.Log("普通收费");
}
}
打折收费
public class CashRebate : CashSuper
{
public override void AcceptCash()
{
Debug.Log("打五折");
}
}
3.创建工厂静态类(工厂只负责生产某一个东西)
public static class CashFactory
{
public static CashSuper CreatCash(string cashname)
{
CashSuper cash = null;
switch (cashname)
{
case "打五折":
cash = new CashRebate();
break;
case "不打折":
cash = new CashNormal();
break;
case "返利":
cash = new CashReturn();
break;
}
return cash;
}
}
4.测试
public class Hello
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Main()
{
CashSuper cashSuper = CashFactory.CreatCash("打五折");
cashSuper.AcceptCash();
}
}
5.打印
策略模式实现
主要思想
策略模式它定义了算法家族,分别封装起来,让他们之间互相替换,此模式让算法的变化,不会影响到使用的客户!
结构图
具体实现
前面的代码和简单工厂一样,主要是工厂去了,加了一个策略管理
/// <summary>
/// 策略
/// </summary>
public class CashContext
{
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper)
{
this.cashSuper = cashSuper;
}
public void GetResult()
{
cashSuper.AcceptCash();
}
}
测试
public class Hello
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Main()
{
CashContext cashContext = null;
string name = "打五折";
switch (name)
{
case "打五折":
cashContext = new CashContext(new CashRebate());
break;
case "不打折":
cashContext = new CashContext(new CashNormal());
break;
case "返利":
cashContext = new CashContext(new CashReturn());
break;
}
cashContext.GetResult();
}
}
打印
PS:降低耦合性(策略和简单工厂的结合)
/// <summary>
/// 策略
/// </summary>
public class CashContext
{
private CashSuper cashSuper;
public CashContext(string name)
{
switch (name)
{
case "普通收费":
CashNormal cashNormal = new CashNormal();
cashSuper = cashNormal;
break;
case "打五折":
CashRebate cashRebate = new CashRebate();
cashSuper = cashRebate;
break;
case "返利":
CashReturn cashReturn = new CashReturn();
cashSuper = cashReturn;
break;
}
}
public void GetResult()
{
cashSuper.AcceptCash();
}
}