Would a singleton GUI be good in this case?

半腔热情 提交于 2020-01-16 07:04:08

问题


I am working on a project where I have lots of classes referring to my GUI (mainly the panels but sometimes the frame itself). So I was thinking that instead of passing the frame as an argument to every constructor and create getters in each class, I would make a singleton instance of the JFrame so all the classes get access to it instead. Is this a good approach or will it just punish my laziness in some way?

Edit: I'm not just lazy, I'm trying to think in models here: For example, let's say I have various Car objects and the Road is my GUI. All Cars should have access to the same Road, and the Road is not a part of a car.


回答1:


There is plenty of opinions in the area, see referenced material below.

My feeling is that we should try to avoid Singletons because "there's no such number as 1".

[This follows on from my theory that "there is no such number as 2". If you have code, that allows for two of something, and only two of something, then you've missed a trick - there's almost certain to be more than two, instead solve how to deal with "many".]

The "no such number as 1 argument" is that just when you thought there could only be one of something there will be some context in which it's possible to have more ... and it's usually very little extra work to allow for more.

Look at your example ... I have various Car objects, they all have access to the same Road? Does that sound like a model of a realistic world? UK Roads and French Roads, any difference? ;-) Why build that "Only One" assumption into your code?

Use of factories and dependency injection of those factories will often be the better answer. Lots more material in answers to this question.




回答2:


The Singleton pattern is considered today to be an "anti-pattern". The problem will become apparent when your Cars will need to be used with a different Road one day.

It will become even more apparent if you decide to unit-test the Cars for themselves. If you can't provide a Mock for the Road, how will you test them? And you won't be able to, since they refer to their Road through a Singleton.

(Obviously there's a workaround by having the Singleton return a MockRoad when in "test-mode", but that just means you're adding testing code into your production code.)




回答3:


A better approach would be to hide the main JFrame behind static methods, but in general it is a good idea if you have only one JFrame object for the whole program to make it static anyway.

Hiding it behind static methods ensures that if you work on this with anyone else you can constrain what you want them to be able to access on the main JFrame, but would be useless for something like a school project etc.



来源:https://stackoverflow.com/questions/1249587/would-a-singleton-gui-be-good-in-this-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!