通过每个子类的单一方法来简化接口的设计模式

问题描述 投票:0回答:1

我目前正在一个代码库中工作,我看到这种模式一次又一次地重复,这对我来说似乎不正确。

有一个具有 N 个方法的基接口或类,同时最多有 N 个子类,它们最多重写其中一个或两个方法。这些方法的其余部分将被覆盖,并且返回 null 被放置在那里。

一个例子是(由于明显的原因不能透露原始代码)-

interface DealService{
  getDealData() 
  getDealRestrictions() 
  getDealRegister() 
  ... 
} 

现在第一个子类仅用实际实现重写 getDealData 并简单地为其余方法返回 null。 第二个子类可能重写 2 个方法,但对所有其他方法返回 null。

我不明白为什么要这样写,我想问设计这样的类的正确模式是什么。

我应该提到,子类对象肯定保存在父接口的列表中,但仍然应该有其他方法来实现相同的目的?

我尝试在互联网和多种人工智能工具上搜索相同的模式,但找不到满意的答案

java design-patterns
1个回答
0
投票

现在第一个子类仅用实际实现重写 getDealData 并简单地为其余方法返回 null。第二个子类可能重写 2 个方法,但对所有其他方法返回 null。

这里似乎违反了接口隔离原则。我的意思是,如果某些方法不需要实现或者返回 null

 那么这可能是违反接口隔离原则的标志。

让我举个例子。例如,您有一个硬盘。你的界面将如下所示:

public interface IHDD { void Write(); string Read(); }
那么你的

HDD

课程将如下所示:

public class HDD : IHDD { public string Read() { return "So far so good!"; } public void Write() { Console.WriteLine("Some info has been written"); } }
几个月后,一个人决定实施

CardReader

。但我们知道 
CardReader
 只能读取,不能写入,所以 
Write()
 决定返回 
null
 甚至值得一些例外:

public class CardReader : IHDD { public string Read() { return "So far so good!"; } public string Write() { return null; } }
解决方案就是将此接口分成两个接口:

public interface IWriteable { string Write(); } public interface IReadable { string Read(); }
然后你的课程将如下所示:

public class HDD : IWriteable, IReadable { public string Read() { return "So far so good!"; } public string Write() { return "Some info has been written"; } } public class CardReader : IReadable { public string Read() { return "So far so good!"; } }
    
© www.soinside.com 2019 - 2024. All rights reserved.