例子
- 妈妈买菜,爸爸买菜,自己买菜
public abstract class AbsBuyVegetable
{
public virtual void BuyVegetable()
{
BuyShuCai();
BuyMeat();
BuyComplete();
}
/// <summary>
/// 买蔬菜
/// </summary>
protected virtual void BuyShuCai()
{
Console.WriteLine("随便买点蔬菜");
}
/// <summary>
/// 买肉
/// </summary>
protected virtual void BuyMeat()
{
Console.WriteLine("随便买点肉");
}
/// <summary>
/// 购买完成回调
/// </summary>
protected virtual void BuyComplete()
{
}
}
public class BaBaBuyVegetable : AbsBuyVegetable
{
protected override void BuyMeat()
{
Console.WriteLine("爸爸买肉食:鱼");
}
protected override void BuyShuCai()
{
Console.WriteLine("爸爸买蔬菜:海带");
}
protected override void BuyComplete()
{
Console.WriteLine("爸爸买菜完毕");
}
}
public class MaMaBuyVegetable : AbsBuyVegetable
{
protected override void BuyMeat()
{
Console.WriteLine("妈妈买肉食:羊肉,牛肉");
}
protected override void BuyShuCai()
{
Console.WriteLine("妈妈买蔬菜:青菜");
}
protected override void BuyComplete()
{
Console.WriteLine("妈妈买菜完毕");
}
}
public class OwnerBuyVegetable : AbsBuyVegetable
{
protected override void BuyMeat()
{
Console.WriteLine("自己买肉食:大羊排");
}
protected override void BuyShuCai()
{
Console.WriteLine("自己买蔬菜:不买");
}
protected override void BuyComplete()
{
Console.WriteLine("自己买菜完毕");
}
}
- 公司-》老板的工作,产品的工作,技术的工作
public abstract class AbsCompanyWork
{
public void Work()
{
ShangWu();
XiaWu();
}
protected virtual void ShangWu()
{
Console.WriteLine("上午:啥也不干");
}
protected virtual void XiaWu()
{
Console.WriteLine("上午:啥也不干");
}
}
public class Boss : AbsCompanyWork
{
protected override void ShangWu()
{
Console.WriteLine("上午:睡觉");
}
protected override void XiaWu()
{
Console.WriteLine("下午:数钱");
}
}
public class ChanPing : AbsCompanyWork
{
protected override void ShangWu()
{
Console.WriteLine("上午:画需求");
}
protected override void XiaWu()
{
Console.WriteLine("下午:与程序员吵架");
}
}
public class JiShu : AbsCompanyWork
{
protected override void ShangWu()
{
Console.WriteLine("上午:敲代码");
}
protected override void XiaWu()
{
Console.WriteLine("下午:改Bug");
}
}
class Program
{
static void Main(string[] args)
{
// BuyVegetableTest();
new Boss().Work();
new ChanPing().Work();
new JiShu().Work();
}
private static void BuyVegetableTest()
{
new OwnerBuyVegetable().BuyVegetable();
new MaMaBuyVegetable().BuyVegetable();
new BaBaBuyVegetable().BuyVegetable();
}
}
个人总结
算法的整体步骤很固定,但其中个别部分易变时,这时候可以使用模板方法模式,将容易变的部分抽象出来,供子类实现。