使用空方法的默认实现的设计模式 [英] Design pattern for default implementation with empty methods
问题描述
是否有特定的设计模式描述了提供非抽象默认实现的情况,该默认实现使用空的NO-OP实现在接口上实现所有或某些方法。这样做是为了减轻子类的负担,以实现自己可能不需要/使用的方法的负担:
Is there a specific design pattern that describes the scenario where a non-abstract default implementation is provided that implements all or some of the methods on the interface with empty, NO-OP implementations. This being done with the intent of alleviating subclasses with the burden of implementing methods that they themselves may not need/use:
public interface MyInterface {
public void doThis();
public void doThat();
public void done();
}
public class MyClass implements MyInterface {
public void doThis() {
// NO-OP
}
public void doThat() {
// NO-OP
}
public void done() {
// Some standard implementation
}
}
public class MuSubClass extends MyClass {
public void doThat() {
// Subclass only cares about doThat()
}
}
我已经多次使用这种模式,包括 SAX框架中Java的DefaultHandler 和 MouseAdapter 。在某些情况下,此类被命名为Adaptors,但是我给人的印象是适配器模式在两个不同的接口之间转换。
I have seen this pattern used a number of times including Java's DefaultHandler in the SAX framework, and MouseAdapter. In somes cases such classes are named as Adaptors, but I was under the impression that the adapter pattern translates between two different interfaces.
鉴于在这些情况下,只有一个声明的接口正在转换为该接口的未定义子集-我不清楚这是如何实现的
Given that in these instances there is only one declared interface that is being translated to an undefined subset of that interface - I am not clear on how this is in the spirit of the adapter pattern.
此外,我还不太清楚它如何遵循 NullObject模式,考虑到某些方法可以实现,并且NullObject传统上是单例。
Furthermore, I don't quite see how this adheres to the NullObject pattern either, given that some methods could have an implementation, and the NullObject is traditionally a singleton.
推荐答案
没有默认实现的设计模式。
我通常会附加 DoNothing
类名的前缀。根据意图,我也使用 Base
或 Default
(后者被广泛使用)。 MouseAdapter
可能应称为 DefaultMouseListener
。
I usually append DoNothing
prefix to the name of class. Depending on it's intent I use also Base
or Default
(the latter is widely used). Probably MouseAdapter
should be called DefaultMouseListener
.
在您需要的情况下,可以使用简单的 DynamicProxy ,则您必须仅返回 nice默认值( null(对象), 0(数字)等)。
In the case you care, you can stub systematically an interface with a simple DynamicProxy, you must return only a "nice" default value (null for Object, 0 for numeric, etc).
顺便说一句,这是一个很好的问题。
BTW this is a very good question.
编辑
此外,它也不是 Stub 或< a href = http://en.wikipedia.org/wiki/Mock_object rel = nofollow noreferrer>模拟:也许可以将其与存根混淆,但意图有所不同。
Furthermore this is neither a Stub or a Mock: maybe it can be confused with a Stub but the intent is different.
这篇关于使用空方法的默认实现的设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!