简体   繁体   English

接口的默认实现? 或保留为空

[英]Default implementation for interface ? or leave as null

So the question is not really easy to understand but I will try my best, lets say I have an interface : 所以这个问题并不是很容易理解,但是我会尽力而为,让我说我有一个接口:

interface OnWindowMoveListener{
    void onWindowMove(MotionEvent motionEvent);
}

Now in my class I have 现在在我班上

OnWindowMoveListener onWindowMoveListener;

public void setOnWindowMoveListener(OnWindowMoveListener onWindowMoveListener){
    this.onWindowMoveListener = onWindowMoveListener;
}

Later in my code the onWindowMoveListener.onWindowMove() is called but I dont want to have to check if the onWindowMoveListener has been set by the user and thus not null, how would I create a default implementation for this listener ? 稍后在我的代码中调用了onWindowMoveListener.onWindowMove() ,但我不想检查用户是否已设置onWindowMoveListener,因此不为null,如何为该侦听器创建默认实现? Would I have to manually implement the interfaces in the main method of my class in case the user doesnt implement them himself or is there another way of doing this ? 如果用户自己没有实现接口,或者有其他方法可以实现,则是否需要在类的main方法中手动实现接口? I have always been checking if the interface has been implemented before calling but want to know if there is a cleaner way of doing this. 我一直在检查调用之前接口是否已实现,但是想知道是否有更干净的方法。 Thanks 谢谢

Doing nullcheck is not a cost operation, but if you really need to avoid it, your best option would be to use the Null Object Design Pattern. 进行nullcheck并不是一项成本操作,但是如果您确实需要避免执行nullcheck,最好的选择是使用Null Object Design Pattern。

Create a implementation of your interface which does nothing, and than use it as default value of the onWindownMoveListener. 创建一个不执行任何操作的接口实现,然后将其用作onWindownMoveListener的默认值。

For more information about this design pattern, consult: https://sourcemaking.com/design_patterns/null_object/java-0 有关此设计模式的更多信息,请访问: https : //sourcemaking.com/design_patterns/null_object/java-0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM