C# OO 设计:仅需要一个抽象方法的情况
我有两个类具有完全相同的逻辑/工作流程,除了一种方法。
因此,我创建了一个抽象基类,其中不同的方法被声明为抽象。
下面是一些示例代码来演示我的设计;任何人都可以提供有关更好方法的建议,或者我是否朝着正确的方向前进。 我没有使用接口,因为派生类 B 和 C 实际上共享大部分逻辑。有没有更好的方法通过依赖注入来完成我在下面所做的事情?
public abstract class A
{
public void StageData()
{
// some logic
DoSomething();
}
public void TransformData();
public abstract DoSomething();
}
public class B : A
{
public override void DoSomething()
{
// Do Something!
}
}
public class C : A
{
public override void DoSomething()
{
// Do Something!
}
}
I have 2 classes that have the exact same logic/workflow, except in one method.
So, I created a abstract base class where the method that differs is declared as abstract.
Below is some sample code to demonstrate my design; can anyone offer suggestions on a better approach or am I heading in the right direction.
I didn't use an interface because both derived classes B and C literally share most of the logic. Is there a better way to do what I am doing below via dependency injection?
public abstract class A
{
public void StageData()
{
// some logic
DoSomething();
}
public void TransformData();
public abstract DoSomething();
}
public class B : A
{
public override void DoSomething()
{
// Do Something!
}
}
public class C : A
{
public override void DoSomething()
{
// Do Something!
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你所做的并没有什么问题。在这个设计中引入依赖注入会很混乱而且矫枉过正——你必须传递一个委托:
你想要使用这种方法的原因很少——一个是如果你需要执行回调。因此,坚持现有的模式,不要试图让事情变得过于复杂。
There is nothing wrong with what you have done. To introduce dependency injection into this design would be messy and overkill - you would have to pass in a delegate:
There would be few reasons why you want to use this approach - one would be if you needed to execute a callback. So stick with the pattern you have, don't try to overcomplicate things.