把公共部分提取到公共类,提供总算法,不一致的地方由子类去完成
public abstract class BaseHandler
{
public virtual void Handle()
{
this.OperationA();
Console.WriteLine("common part");
this.OperationB();
}
protected virtual void OperationA()
{
Console.WriteLine("operationA in base handler");
}
protected virtual void OperationB()
{
Console.WriteLine("operationB in base handler");
}
}
public class SubClass : BaseHandler
{
public override void Handle()
{
base.Handle();
}
protected override void OperationA()
{
Console.WriteLine("implementation operationA in sub class");
}
protected override void OperationB()
{
Console.WriteLine("implementation operationB in sub class");
}
}
BaseHandler bh = new SubClass();
bh.Handle();