Reputation: 15341
I am trying to understand how the UI components should be wired in Java. As far as regular "server" classes are concerned, I am trying to use interfaces and inject everything using Spring. In case of the UI, should similar approach be used?
To be more precise, let's consider the following:
class Panel1 extends JPanel{
public Panel1(Service service, DBConnector db);
}
class Panel2 extends JPanel{
public Panel1(Delegate delegate, Executor exec);
}
class MainFrame{
public MainFrame(Service service, DBConnector db, Delegate delegate, Executor exec){
Panel1 p = new Panel1(service, db);
Panel1 p = new Panel1(delegate, exec);
}
}
vs
class MainFrame{
public MainFrame(Panel1 panel1, Panel2 panel2){
}
}
I just wanted to get a general feeling what is more appropriate in the UI world, if it at all differs from the regular classes (possibly with the fact that there could be many panels involved in the main frame)
Upvotes: 0
Views: 202
Reputation: 328624
I haven't seen anyone using DI in for UIs; this might be because DI is a pretty new concept (compared to building UIs) or that most people fled to MVC after living in UI hell for a while and MVC solves all the problems.
Also, most UIs are static in the sense that you can open and close windows/dialogs with buttons but you can't replace one dialog with another. It would be handy but only if I, as a user/consumer, could do that. There is little point to write two dialogs that do the same thing and then use DI to wire one or the other; you either need two different dialogs or only one.
When UIs support to be extended (like Eclipse), they use a plugin system to load UI elements at runtime and the code in there discover menus, toolbars, etc. and add elements.
e4 (the latest code base for Eclipse) uses DI for many things but not for building the UI. Again, the UI is usually static in the sense that you never have two or more services in a certain place from which the user could chose from.
So using DI might make sense but it's probably ground breaking work (i.e. you'll have to explore the possibility space and find the low complexity valleys yourself).
Upvotes: 3