开发者

GWT use of interface instead of widget

in a définition of a widget, what is a开发者_Go百科 better practice, and why, use the widget himself or the type "higher", example, it's a better practice to do

1) Button myButton; or 2) Hastext myButton; (and set a button later)

thanks for your answer.


It is usually a good idea to use "higher" types or interfaces. By doing this properly you can hide implementation details. The code that uses an object looks at it as the one of a higher type and it is not important what is actually hiding behind it. This is good because you can easily change an implementation of the object without breaking anything.

For example when defining a panel in an application you should use Panel class instead of its implementation e.g. HorizontalPanel or VerticalPanel.:

Panel myPanel; 

Then you can create a proper implementation of it, e.g HorizontalPanel:

myPanel = new HorizontalPanel();

If you then later decide to change myPanel to be VerticalPanel you will not have to change anything in the code that uses myPanel. Everything will work just fine.

However you must remember that you will be only able to use methods available in Panel class. Additional methods defined in e.g. HorizontalPanel will not be accessible. And this is actually what you should remember when choosing the type of your widgets. Your widgets should be of types which provide methods which you want to use.

In your example using HasText instead of Button isn't probably a good idea because HasText has only methods for setting and getting a text and you probably also want to have access to addClickHandler method available in Button and a few more.

So to summarize it is good to use "higher types" but they should not be "too high" to be useful.


The answer to that lies in the Model-View-Presenter pattern, that was introduced in last years Google IO presentation by Ray Ryan. There's also an official tutorial/docs - part 1 and part 2. There are also a number of questions here on SO that cover that topic :)

And a quick answer to your question (that will make more sense once you get familiar with MVP): use interfaces in the Presenter and their implementations in the View :) That way your Presenter stays oblivious to the underlying implementation/Widget you actually used (was it a Button? Or a Label? It doesn't matter, they both implement HasText).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜