以多种会员下单为例
- UML图:
- 代码实现:
/// <summary>
/// 创建订单模板
/// </summary>
public abstract class BaseCreateOrder
{
public abstract bool CheckParameters(decimal price, int count);
public abstract void SaveData(decimal price, int count);
public virtual void DoExtend(decimal price, int count)
{
Console.WriteLine("亲爱的顾客,您的订单已生成,价格为{0},数量为{1}", price, count);
}
public void CreateOrder(decimal price, int count)
{
if (CheckParameters(price, count))
{
SaveData(price, count);
DoExtend(price, count);
}
else
{
Console.WriteLine("创建订单失败,参数不合法");
}
}
}
/// <summary>
/// 普通会员下单
/// </summary>
public class NormalCreateOrder : BaseCreateOrder
{
public override bool CheckParameters(decimal price, int count)
{
//普通会员下单价格不能低于100
if (price < 100)
{
Console.WriteLine("价格太低了");
return false;
}
Console.WriteLine("下单参数检测合法");
return true;
}
public override void SaveData(decimal price, int count)
{
Console.WriteLine("存入数据库");
}
}
/// <summary>
/// VIP会员下单
/// </summary>
public class VIPCreateOrder : BaseCreateOrder
{
public override bool CheckParameters(decimal price, int count)
{
Console.WriteLine("下单参数检测合法");
return true;
}
public override void SaveData(decimal price, int count)
{
Console.WriteLine("存入数据库");
}
public override void DoExtend(decimal price, int count)
{
Console.WriteLine("尊敬的VIP顾客,您的订单已生成,价格为{0},数量为{1}", price, count);
}
}
- 调用端代码:
class Program
{
static void Main(string[] args)
{
decimal price = 99;//价格
int count = 10;//数量
Console.WriteLine("*******************普通会员下单********************");
BaseCreateOrder normalCreate = new NormalCreateOrder();
normalCreate.CreateOrder(price, count);
Console.WriteLine("*******************VIP会员下单********************");
BaseCreateOrder vipCreate = new VIPCreateOrder();
vipCreate.CreateOrder(price, count);
Console.WriteLine();
Console.ReadLine();
}
}
- 运行效果:
- 总结
模板方法模式,是通过把不变的行为搬移到超类,去除子类中的重复代码来提现它的优势,变化的则在各个子类进行实现。
代码下载地址:链接:https://pan.baidu.com/s/1GXKA7sinwcrrixFipN4hYA e2f5