Singleton within MVC

I am developing an application using MVC, and was wondering if it appropriate to use the singleton pattern on certain views, such as modal dialogs. It seems to me that this would make the code simpler and easier to read. What would be the advantages/disadvantages of this? Thanks for any input.

Caleb

[313 byte] By [maxcaleb] at [2007-9-27 20:34:45]
# 1

Singleton can be used if You truely need only one instance of the class. The singleton object should be available from a well known source (like a subsystem interface creates it, the creation should be loosely coupled ). Please see if scoping the views solves the problem. Anyway it depends on the context, if your view is going to be a generic view that is used in many sub packages then you might want to consider to make it singleton. But it depends on the context.

- Karthicraja

karthicraja at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 2

Well, the Singleton pattern doesn't necessarily mean one instance of a class (though that's from where its name is derived), but a controlled number of instances of a class. Example say you have only 4 connections can be made to your system at once, a Singleton pattern can be used to ensure that only 4 Instances can be created.

NG

NineGraves at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 3
Agreed, variants of singleton pattern don抰 necessarily mean one instance. So let me rephrase it as "Variants of singleton can be used if you truly need fixed number of instances of the class."- Karthicraja
karthicraja at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 4

> Agreed, variants of singleton pattern don聮t

> necessarily mean one instance. So let me rephrase it

> as "Variants of singleton can be used if you truly

> need fixed number of instances of the class."

>

> - Karthicraja

Yes and a good example of that are the servlets I guess.

nome02 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 5

I think some Singletons in GUIs are useful, as you say they make the code more readable, and I've also heard that they might assist performance by allowing the compiler to do some compile time optimisations.

For my project the "main" JDesktopPane is in a Singleton since there is only ever one of them. Like you, I have some "one off" dialogs/windows which are also in singletons.

It's nice to see a question that isn't someones homework !

(or at least doesn't look like it)

john3136 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 6

>For my project the "main" JDesktopPane is in a Singleton

>since there is only ever one of them.

If i make an assumption that JDesktopPane is a root window that is refered in different subpackages. Then it could create a dependency in the subpackages with the Singleton class. This will lead to less reusbility is it? Did you face this problem.

- Karthicraja

karthicraja at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 7

me>For my project the "main" JDesktopPane is in a Singleton

Karthicraja> If i make an assumption that JDesktopPane is a root

Karthicraja> window that is refered in different subpackages. Then

Karthicraja> it could create a dependency in the subpackages with

Karthicraja> the Singleton class. This will lead to less reusbility

Karthicraja> is it? Did you face this problem.

Your assumption is correct, and yes the dependancy thing is there a bit.

I have not found it to be an issue, presumably because you get at the

single instance via a static function.

I contend that this is a reasonable design. There is only one "root"

window so it should be a singleton thus enforcing that there is only

one. When another package needs to use something in that window, it

can.

I guess that is where the question of good design really arises. Should

another package really need to access anything in the main window, or

does doing this mean my class decomposition is not adequate ?

john3136 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 8
I think this is a pretty good topic to discuss, let me quickly collect some design decisions before starting. - Karthicraja
karthicraja at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 9

a 'single factory' :)

> Well, the Singleton pattern doesn't necessarily mean

> one instance of a class (though that's from where its

> name is derived), but a controlled number of instances

> of a class. Example say you have only 4 connections

> can be made to your system at once, a Singleton

> pattern can be used to ensure that only 4 Instances

> can be created.

> NG

mchan0 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 10

All designs take place in its own context. And whatever design trade offs you choose to make a design reasonable for that context might be bad for other contexts. So it is fairly difficult to conclude that a design is right or wrong or perfect.

So before discussing this topic, lets fix some common ground about the objectives we would want to meet by our design. A good design should be modular, understandable, integrative, continuous, and protected.

1) Modular - a complex system is broken down to a collection of integrated modules; each module has a clear purpose and narrowly specified interface.

Our example in this case is though broken down to integrated modules; by directly accessing the JdesktopPane singleton class the subsystem owns the control structure. This might lead to inconsistency as low-level module skips different levels in the hierarchy and access the top-level objects. While evolving this design could lead to a problem of high dependency.

To maintain high modularity we could apply a top-down decomposition approach where the control flows through top to bottom objects, and the subsystems only reacts to the requests of the high level objects. In our case this means the top-level object attaches the subsystem objects to it. Means that probably instead of your view attaching itself with the JdesktopPane. Some top-level class, which has the scope for both the subsystem class and the JdesktopPane, binds them together. So mostly scoping of objects and subsystem can solve this problem.

2) Integration - usability of modules by different systems.

Our example in this case is tightly coupled with the JdesktopPane singleton class, that the individual sub-modules are reusable. To get good reusability the subsystem should not make assumptions about any high level objects. If a system evolves the other way it could be a consequences of a bottom up decomposition. This is a violation of law of demeter.

3) Understandability ?individual modules and objects in isolation should be understandable by human reader. An object, a module, a subsystem is understandable if it doesn齮 show any surprises from it. In our case apart from it is purpose if it accesses the JdesktopPane object to attach itself, then it is a surprise, the human reader has to refer to that singleton class unnecessarily to trace what is happening.

4) Continuity - small change in specification results in changes in only a few modules, does not affect the architecture. In our case instead of using JdesktopPane if I want to use different window type which has a different interface, there might be at lot of places the changes has to be made. So it is good to prevent from depending upon volatile objects.

5) Composability - freely combine modules to produce new systems. Since it brings transitive coupling composability is difficult.

6) Decomposability - decompose problem into smaller subproblems that can be solved separately. Refering a top level class from a low level class brings a cyclic dependency which leads to high levels of references that the decompsition is not easy.

7) Protection - Effects of an abnormal run-time condition is confined to a few modules

when the control is left to the submodule the top level module loosses the protection it is supposed to have. The control is handed to the subsystem, which in a complex system can create problems.

- Karthicraja

karthicraja at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 11
Some interesting (and valid) comments there.I'll need some time to pull a sensible response together...
john3136 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 12

Re the introduction - all too true. In my case the biggest factor driving tradeoffs are commercial considerations.

Basically we have a short design period and some working prototypes and

so there is no budget to re-work the design to be "theoretically perfect".

On a side note: I'm pretty much stuck with the design I have now, but if I learn some new design tricks then my faith in the forums (sadly quite low due to "do my homework", "fix my classpath" and "how do I add two numbers together" type questions)

1) Modular

Whether this is a problem depends on the types of operations that the singleton has. To be completely honest, I've forgotten the details ;-).

The singleton is mainly used as the central point in an MVC architecture. Each InternalFrame (view) can have buttons, and they all trigger singleton to send a message to all the other views.

Realistically, this design is a one off - it will be used in this product and does not have to support being hugely generic (which is a noble aim, but doesn't always mesh with commercial reality). This means that reducing dependancy is not high on the list of priorities.

2) Integration

Your point is correct and I've identified bits that should be reusable, and they do not use the singleton. The parts that do use it are deemed to be "application specific".

In Demeter terms, I almost scrape in because I've got a fairly flat package hierarchy (which is a whole other topic of discussion).

This is where "implementation convenience" comes in over "theory". It strikes me that you could create one or more interfaces on the singleton and use those interfaces from other packages which is probably a more complete OO approach and helps integration because any class that implemented the interface could be used in place of the singleton.

That's a point that I'll take away and stick in my toolbox for future reference !

3) Understandability

Again I agree - my justification is that the singleton is reasonably simple and only used for a few specific things and so I don't think the design we are discussing here necessarily works against understandability. Obviously if the singleton has 500 methods and the users of it call every single method 10 times each, then there is a problem (probably bigger than just understandability ;-)

4) Continuity

Yet again you are right and my defense boils down to "This was designed (not just thrown together) and so the singleton is not overly volatile".

If I remember correctly, the actual JDesktopPane is hidden from the users (who just call methods) and so stuff like changing the window would be a single change.

5) Composability

I think I've covered this. For me, commercially this is explicitly not a requirement. It is a nice thing to do, but it does take a bit longer to write reusable code than to "slap it together". In a perfect world, you'd do it once and do it properly !

6) Decomposability

Now we get interesting. I disagree with you here. You can look at the singleton as a "utility library" - the methods it contains solve particular problems which may be part of larger problems. The fact they are located in a singleton does not impact that.

7) Protection

Realistically I'm not sure how you can solve this issue - I have some particular internal frames in packages. They all reference the desktop pane in some way (even if just by the normal Swing methods and not by me adding code).

I have a feeling I'm not quite grasping your point on this one...

...I wonder if we've scared off the original poster yet :-)

john3136 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 13

I'm still lurking around, you guys bring up some interesting points, although I must admit some of it is a little over my head. I have the luxury of developing my app in my own time, and therefore have changed the design multiple times in order to learn more and get it how I want it. In my case, reusability has been important, so I have abandoned the idea of using singleton, although it probably could be used for certain parts.

maxcaleb at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 14

Iteration is the best way to learn design.

As is human nature, I've defended my design as appropriate for my needs (the bottom line is if it does the job, it's right ;-)

My singleton is actually an iteration too - my first version did not use a singleton, but I found I was passing the reference around so much it made sense to centralise it.

As I mentioned above, having sat back and looked at what I've done,

there are a couple of places where using some interfaces is a better

approach than my singleton.

I always try to design/write reusable code, but at some point as a professional engineer you have to draw a line as to what is reusable/support stuff and what you just have to write for the job.

In a perfect world you would just pick components (beans?) off the shelf, glue them together, tailor them to your needs and then you're done. In reality it doesn't work like that !

john3136 at 2007-7-7 1:39:16 > top of Java-index,Other Topics,Patterns & OO Design...
# 15

In my previous explanation i have set some attributes for a good design (based on theories & Experience). As you have said i agree that not all the design requires all these parameters. It is true a good design gives the right solution for the context and the cost.

Developments that you feel can be reused should be designed generically so that you can save time the next time (You will not worry about fixing bugs in that, is it) I would like to recommend that ?be conscious about what you design?. Capturing design attributes like this will help in quantifying your design and give awareness about what is emerging out of the design.

A good design reduces dependencies between disparate parts of the program, encourages reuse of code, components, and modules. Increases extensibility while reducing maintainability.

More about decomposability and protection.

Decomposability

I am trying to see is that a component should assemble hierarchically to a larger part; if it doesn?t come through that way we have to see if defining a appropriate scope can solve that. If you can decompose a system without a redundant tear then you can assemble it easily too.

Protection

Suppose that you are giving plugin support to your application, in our case the plugin might access the singleton and render it. In this case if you hand over the parent control to the plugin component then a plugin developer can take control of the total application and mess it. By exposing the JDesktopPane through a global object reference, the abstraction that the application supposed to have is lost. It is just a scenario came in to my mind.

- Karthicraja

karthicrajaa at 2007-7-18 15:50:46 > top of Java-index,Other Topics,Patterns & OO Design...
# 16

Agree with your points.

Decomposability

In my system, the singleton really is "the biggest piece". It is the

application that every other window is a part of.

It's almost a "service provider" to the other components.

Protection

Agree. That's why I would have a static 'addWindow()' method for other components to call rather than exposing the JDesktopPane for everyone to manipulate as they saw fit.

john3136a at 2007-7-18 15:50:46 > top of Java-index,Other Topics,Patterns & OO Design...