Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Basically I have one Tree view which uses a single DefaultTreeModel.

Is it okay to use singleton for Tree extending JTree and another singleton for TreeModel extending DefaultTreeModel?

If not, what is the reason to avoid using singleton for each object?

share|improve this question
2  
What is the reason to make them singletons? Does something break badly if there are two of them? –  Peter Taylor Jun 28 '11 at 7:26

1 Answer 1

Singleton pattern is usually best when an instance has to be unique in its usage across the entire program. If you're using swing, it's probably not a good idea to use singleton unless swing already uses the Singleton pattern to give you the instance in the first place (thus defeating the purpose of writing it yourself). In general, singleton should be avoided, because in a way, it's like using global variables in C++. Having a single instance available across your entire program means potentially losing scope of where it gets used and what state it should be in. It ultimately adds to confusion in your program and if it could be avoided by sharing one instance, better to do so.

What you probably want to do is reuse the same instance of Tree, and that effect you can achieve simply by passing it as a parameter to whatever frame you're trying to create. The Tree object can define its own view, and thus by using a single instance of Tree, you're also ensuring that you're using a single instance of its view (assuming you don't change it later).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.