脚本
我想提供一种可选择在我的工作类中添加回调的可能性。 这种回调的界面可能看起来像这样:
public interface Callback<T> { void callback(final T data); }理念
所以我想知道是否有一个无操作回调,这看起来像这样:
@SuppressWarnings("rawtypes") public class NopCallback implements Callback { public static final NopCallback CALLBACK = new NopCallback(); @Override public void callback(final Object data) { // do nothing } }实际问题
我已经发现Nop变体似乎表现更好(通过调用doWork(...)几次1000次并测量每个变体的持续时间)。 我并不完全满意的是需要@SuppressWarnings 。 我知道我可以摆脱它们但是在我的每个工作类中我都需要一个自己的NopCallback实例。
长话短说,就是在干净的代码 , 可读性 , 性能等方面使用这样的无操作回调是一个好主意还是还有其他(优雅的)替代方案吗?
Scenario
I want to provide a possibility to optionally add callbacks in my working classes. An interface of such a callback may look something like that:
public interface Callback<T> { void callback(final T data); }Idea
So I wonder if it is a good idea to have a no-operation callback instead which looks something like this:
@SuppressWarnings("rawtypes") public class NopCallback implements Callback { public static final NopCallback CALLBACK = new NopCallback(); @Override public void callback(final Object data) { // do nothing } }Actual question
I've already found out that the Nop variant seems to perform better (by calling doWork(...) a few 1000 times and measure the duration with each variant). The thing I'm not totally happy with is the need of the @SuppressWarnings. I know I could get rid of them but then I'd need an own instance of NopCallback in each of my working classes.
Long story short, is the use of such a no operation callback a good idea in sense of clean code, readability, performance etc. or are there any other (elegant) alternatives?
最满意答案
这看起来很优雅。 它与Collections.emptyList()基本相同,它总是返回相同的空的不可变列表。 我不会把它变成公共类,但会使用工厂方法来获取它,以确保警告只在一个地方,其余的代码是类型安全的:
@SuppressWarnings("unchecked") private static final Callback NOP = new Callback() { @Override public void callback(final Object data) { // do nothing } }; @SuppressWarnings("unchecked") public static final <T> Callback<T> nop() { return (Callback<T>) NOP; }这就是Collections.emptyList()的实现方式。
That looks quite elegant to me. It's basically the same idiom as Collections.emptyList(), which returns always the same, empty, immutable list. I wouldn't make it a public class though, but would use a factory method to get it, to make sure the warning is only at a single place, and the rest of the code is type-safe:
@SuppressWarnings("unchecked") private static final Callback NOP = new Callback() { @Override public void callback(final Object data) { // do nothing } }; @SuppressWarnings("unchecked") public static final <T> Callback<T> nop() { return (Callback<T>) NOP; }This is how Collections.emptyList() is implemented.
更多推荐
发布评论