c# - 我应该使用设计模式将抽象基类中的逻辑放在其他地方吗?
问题描述
我目前正在开发一个 .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 的逻辑留在我的抽象基类中,还是将其放在其他地方?
您认为什么是某些逻辑的最佳位置,该逻辑由几个继承类使用,但不是全部 - 所有继承类都不能使用?
非常感谢!
解决方案
推荐阅读
- parsing - 从 Scrapy 蜘蛛类中的另一个文件调用 HTML 标签并解析它们
- javascript - 使用 html-dock-js-typescript 生成的 word 文件中的问题
- c# - 如何让单人游戏中的角色走在特定的路线上?
- python-3.x - Python(3.x): print(string , end='') 导致突出显示模符号 %
- python-3.x - 当我抓取数据 python selenium 时,tbody 不会出现
- jenkins - 如何拥有模块化的 Jenkins 流水线?
- apache-kafka - 监控 Kafka SSL 证书的有效性
- javascript - 无法离线使用下载的库(pdfmake)
- .htaccess - .htaccess 中的阶段 301 重定向
- python - 如何在 SQLAlchemy ORM 中使用“as”选择查询并连接表