代码重构。 类 实现相同的接口
Code refactoring. Classes implementing same Interface
我有 4 个 Classes
实现了相同的 Interface
。 类 例如
ABC
、XYZ
、LMN
,现在classLMN
的实例可能belongTo
[=14=的实例] 表示也可以是子对象。如果一个对象是一个子对象,那么它不应该拥有所有可用的独立对象的方法,否则它的功能会略有不同。
处理这种情况的最佳做法通常是什么。
这似乎违反直觉,但您可能想考虑实现第二个接口 ChildInterface
,即 Interface
的 parent。将您希望子级可用的方法子集放在那里。
public interface ChildInterface{
...
}
public interface Interface extends ChildInterface{
//add methods you don't want Children to have
}
public class XYZ implements Interface{
...
}
然后在你的Interface
界面或者XYZ
class,有个方法
public ChildInterface getChild();
因为你所有的 classes 都实现了这两个接口,这将编译得很好,它会保证返回的对象仅限于 ChildInterface
.
中的方法
我有 4 个 Classes
实现了相同的 Interface
。 类 例如
ABC
、XYZ
、LMN
,现在classLMN
的实例可能belongTo
[=14=的实例] 表示也可以是子对象。如果一个对象是一个子对象,那么它不应该拥有所有可用的独立对象的方法,否则它的功能会略有不同。
处理这种情况的最佳做法通常是什么。
这似乎违反直觉,但您可能想考虑实现第二个接口 ChildInterface
,即 Interface
的 parent。将您希望子级可用的方法子集放在那里。
public interface ChildInterface{
...
}
public interface Interface extends ChildInterface{
//add methods you don't want Children to have
}
public class XYZ implements Interface{
...
}
然后在你的Interface
界面或者XYZ
class,有个方法
public ChildInterface getChild();
因为你所有的 classes 都实现了这两个接口,这将编译得很好,它会保证返回的对象仅限于 ChildInterface
.