[英]Polymorphism using interface
从接口IPrintHandler派生的BasePrintHandler类,并实现所需的功能。 作为库提供
应用程序必须提供不同于库的功能(SendToPrint)。 现在,为此,我从BaseClass以及从接口派生了一个类。
为此,我创建了一个示例
interface IPrintHandler
{
void SetPage();
void SendToPrint();
}
class BasePrintHandler : IPrintHandler
{
void IPrintHandler.SendToPrint()
{
Console.WriteLine("in the base print handler");
}
void IPrintHandler.SetPage()
{
Console.WriteLine("in the setpage");
}
}
class ChildPrintHandler : BasePrintHandler,IPrintHandler
{
private BasePrintHandler m_Printhandler;
public ChildPrintHandler()
{
m_Printhandler = new BasePrintHandler();
}
void IPrintHandler.SendToPrint()
{
Console.WriteLine("in the derive class");
IPrintHandler aPRinthandler = m_Printhandler as IPrintHandler;
aPRinthandler.SendToPrint();
}
}
class Program
{
static void Main(string[] args)
{
IPrintHandler aLayouthandler = new ChildPrintHandler();
aLayouthandler.SendToPrint();
aLayouthandler.SetPage();
Console.Read();
}
}
还算不错,但是在这种模型中,我宁愿稍微做些不同。 您的基类可能实现某些默认行为(可以完全替换),或者可能实现某些最需要的行为,子类必须记住要调用基类。 当我编写接口并提供基类以提供样板实现时,我将使用受保护的覆盖更进一步:
public interface IPrinter
{
void SetPage();
void SendToPrint();
} // eo interface IPrinter
public class BasePrinter : IPrinter /* Could well be abstract */
{
protected virtual void SetPageImpl() { } /* Also could be abstract */
protected virtual void SendToPrintImpl() { } /* ........ditto ..... */
// IPrinter implementation
public void SetPage()
{
SetPageImpl();
// can do other stuff here. Will always be called!
} // eo SetPage
public void SendToPrint()
{
SendToPrintImpl();
// ditto
}
} // eo class BasePrinter
public class ChildPrinter : BasePrinter
{
// we only do something different when setting a page
protected override void SetPageImpl()
{
// ChildPrinter-specifics
} // eo SetPageImpl
} // eo class ChildPrinter
这样,我们保留了接口的约定,提供了将始终被调用的样板代码,并允许其他类更改行为。 在大多数情况下,我倾向于使用抽象保护功能来实现上述功能。 我也不必记住调用基类实现,或以什么顺序调用(重写的开始或结束?)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.