首页 > 解决方案 > 我应该使用设计模式将抽象基类中的逻辑放在其他地方吗?

问题描述

我目前正在开发一个 .NET 4.7.1 应用程序。我们在项目中不使用依赖注入。

我为我的消息处理程序实现了一个抽象基类。

目前,我的抽象基类中有一种通用逻辑方法,它并未在所有继承子类中使用。它实际上以某种方式弄乱了我的继承类,因为它添加了在所有继承子类中都不需要的逻辑。

也许我应该把逻辑放到一个单独的类中,或者你知道一个好的设计模式可以使用吗?不过,我不太确定。我的代码如下所示:

public abstract class BaseVegetableHandler
{
   public virtual int HandleMessage(string message) => throw new NotImplementedException();

   // this method has logic which is used in some inheriting sub classes, but not all -> where should I put this logic?
   protected void SaveSalad(string vegetables) 
   {
      // some logic, which is only used in some inheriting classes, but not all!
   }
}

public class TomatoHandler : BaseVegetableHandler
{
   // Handle message is overriden in all inheriting sub classes
   public override HandleMessage(string message)
   {
      // some logic and then:
      SaveSalad(vegetables); // => this method is implemented in my abstract base class, but not used in all inheriting classes, nor can be used in all inheriting classes... where should I put this logic?
   }
}

// I thought about putting this logic into its own helper/handler class, this way I could just create a new instance in each class, that needs the logic:
public class SaladHelper
{
   public void SaveSalad(string vegetables) 
   {
      // some logic
   }
}

我不确定是否应该将 SaveSalad 的逻辑留在我的抽象基类中,还是将其放在其他地方?

您认为什么是某些逻辑的最佳位置,该逻辑由几个继承类使用,但不是全部 - 所有继承类都不能使用?

非常感谢!

标签: c#design-patternsabstract-classdecorator

解决方案


推荐阅读