基于委托的模板方法:从而具体实现方法可以不依赖于抽象类,达到解耦的目的
几点注意:
1.delegate声明在模板类中
2.在类DoCompA和DoCompB中定义与委托相同的方法
3.在Main()中组装委托链,调用tm.DoComp()意味着这是一个模板方法(非抽象中方法调用抽象方法)
public class TemplateMethod
{
public delegate void Do();
public Do myDo;
public void DoComp()
{
myDo();
}
}
public class DoCompA
{
public void c1()
{
//Do something
}
public void c2()
{
//Do something
}
}
public static class DoCompB
{
public static void c3()
{
//Do something
}
}
public class MainClass
{
static void Main()
{
DoCompA a = new DoCompA();
TemplateMethod tm = new TemplateMethod();
tm.myDo += new TemplateMethod.Do(a.c1);
tm.myDo += new TemplateMethod.Do(a.c2);
tm.myDo += new TemplateMethod.Do(DoCompB.c3);
tm.DoComp();
}
}
{
public delegate void Do();
public Do myDo;
public void DoComp()
{
myDo();
}
}
public class DoCompA
{
public void c1()
{
//Do something
}
public void c2()
{
//Do something
}
}
public static class DoCompB
{
public static void c3()
{
//Do something
}
}
public class MainClass
{
static void Main()
{
DoCompA a = new DoCompA();
TemplateMethod tm = new TemplateMethod();
tm.myDo += new TemplateMethod.Do(a.c1);
tm.myDo += new TemplateMethod.Do(a.c2);
tm.myDo += new TemplateMethod.Do(DoCompB.c3);
tm.DoComp();
}
}