【发布时间】:2012-04-23 14:03:40
【问题描述】:
我有一个非常基本的问题(我不知道为什么我无法思考)。
我正在尝试做一些多态性。
我的界面是这样的:
Public interface Iplugin
{
void doSomthing(string _str);
}
我也有一些实现这个接口的插件类
public class plugin1:Iplugin
{
void doSomthing(string _str)
{
if (_str=="1")
{
// do somthing 1
}
}
}
public class plugin2:Iplugin
{
void doSomthing(string _str)
{
if (_str=="2")
{
// do somthing 2
}
}
}
public class plugin3:Iplugin
{
void doSomthing(string _str)
{
if (_str=="3")
{
// do somthing 3
}
}
}
所以我有主类,我希望它调用所有插件
但我希望它保存 OCP(开闭原则),所以如果我将来添加另一个插件类,主类不会改变。
这是主类
public class mainApp
{
Iplugin _context;
mainApp()
{
_context= new //new what??
}
bool func(string str)
{
_context.doSomthing(str);//I would like it to invoke all the plug in and also a future plugins that I will add
}
}
【问题讨论】:
-
不确定真正的问题是什么?您肯定需要在其中进行一些继承并使 doSomething 成为虚拟的吗?
-
制作插件并不是一项微不足道的编程任务,这通常是您不/不能遵循许多标准实践的原因。如果你只是想找一个例子来学习编程,我建议你远离插件,至少现在是这样。如果这不仅仅是一个学术练习,请随意忽略我。
标签: c# interface polymorphism implementation open-closed-principle