问题描述
Android中的是策略模式的示例吗?在另一个Stackoverflow 中,接受的答案表示它是观察者模式。
类似的代码可以理解问题。
公共接口OnClickListener {
void onClick(View view);
}
公共类Button扩展了View {
私人OnClickListener侦听器;
void clicked(){
//一些代码
if(listener!= null){
listener.onClick(this);
}
//其他一些代码
}
public void setOnClickListener(OnClickListener listener){
this.listener = listener;
}
}
我的推理是相信其策略模式而不是观察者模式:
- 在这里我们看到
Button
类没有侦听器列表(观察者),但只能有一个听众。 - 它一次将一部分方法委派给其实例成员:侦听器。
-
OnClickListener
类似于策略,其中用户代码实现了单击按钮后将被调用的策略(方法)。 -
OnClickListener $ c $的不同实现c>可以在运行时传递给
Button
对象,并且可以在运行时更改行为。 (单击相同的按钮可能会显示带有OnClickListener
的一种实现的弹出窗口,并且如果OnClickListener $ c的另一种实现可能会向服务器发送请求$ c>被传递。)
这是页面上观察者模式的意图293。
严格来说,代码示例不是观察者,因为一对多关系更像是一对一。但是,按照第315页的意图,我也不会将其称为策略。
在语义上,侦听器不是一种算法;即,响应事件与执行计算的目的不同。此目的在语法上体现了 onClick()
方法为 void
的位置,因此其行为更像侦听器。
Is OnClickListener in android an example of Strategy pattern ? In another Stackoverflow question accepted answer says it is Observer Pattern.
Similar Code to understand the question.
public interface OnClickListener{
void onClick(View view);
}
public class Button extends View{
private OnClickListener listener;
void clicked(){
//some code
if(listener != null){
listener.onClick(this);
}
//some other code
}
public void setOnClickListener(OnClickListener listener){
this.listener = listener;
}
}
My reasoning to believe its strategy pattern and not observer pattern :
- Here we see
Button
class does not has a list of listeners(Observers) but can have only one listener. - It delegates a part of method to its instance member : listener at a time.
OnClickListener
is similar to a strategy where user code implements an strategy (method) to be invoked once button is clicked.- Different implementations of
OnClickListener
can be passed toButton
object during run time and behavior can be changed during run time. (Same button upon clicked may show a pop up with one implementation ofOnClickListener
and may send a request to server if another implementation ofOnClickListener
is passed.)
Here is the intent of the Observer Pattern from page 293.
Strictly speaking, the code example is not an Observer then, because the one-to-many relationship is rather one-to-one. However, I would not call this a Strategy either, per its intent from page 315.
Semantically, a listener is not an algorithm; i.e. responding to an event is a different purpose from performing a calculation. This purpose manifests syntactically where the onClick()
method is void
and therefore behaves more like a listener.
For that reason, I would call the code example a degenerate form of the Observer Pattern. It looks to me like an Observer attempt that didn't quite meet the qualifications. I wouldn't dignify the attempt by associating it with another pattern.
这篇关于使用OnClickListener()是策略模式的示例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!