C# OO 设计:仅需要一个抽象方法的情况

发布于 2024-12-22 11:59:49 字数 596 浏览 1 评论 0原文

我有两个类具有完全相同的逻辑/工作流程,除了一种方法。

因此,我创建了一个抽象基类,其中不同的方法被声明为抽象。

下面是一些示例代码来演示我的设计;任何人都可以提供有关更好方法的建议,或者我是否朝着正确的方向前进。 我没有使用接口,因为派生类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

得不到的就毁灭 2024-12-29 11:59:49

你所做的并没有什么问题。在这个设计中引入依赖注入会很混乱而且矫枉过正——你必须传递一个委托:

public class ABC
{
    public ABC(Action z)
    {
        _doSomethingAction = z;
    }

    public void DoSomething()
    {
        _doSomthingAction.Invoke();
    }


    private Action _doSomthingAction;
}

你想要使用这种方法的原因很少——一个是如果你需要执行回调。因此,坚持现有的模式,不要试图让事情变得过于复杂。

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:

public class ABC
{
    public ABC(Action z)
    {
        _doSomethingAction = z;
    }

    public void DoSomething()
    {
        _doSomthingAction.Invoke();
    }


    private Action _doSomthingAction;
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文