Good case for Singletons?

后端 未结 10 1596
臣服心动
臣服心动 2021-01-05 07:24

I have an application that has several classes used for storing application-wide settings (locations of resources, user settings, and such). Right now these classes are just

10条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 07:49

    Sometimes what people think belong as Singleton objects really can be private members of a class. Other times they should be unique global variables. Depends on what the design needs them to be.

    If there should be one, and exactly one instance of an object: use a Singleton. By that, I mean if the program should HALT if there's more than one object. A good example is if you're designing a video game that only supports rendering to a single output device, ever. Trying to opening the same device again (shame on you for hardcoding!) would be forbidden. IMHO a case like that often means you shouldn't be using classes in the first place. Even C allows you to trivially encapsulating such a problem without the complexity of making a Singleton class, and still maintain the elements of OO that apply to a singleton. When you're stuck in a language like Java/C# , the singleton pattern is what you've got to work with, unless purely static members will do the trick on their own. You can still simulate the other way through those.

    If it's merely a case of interfacing objects, you probably should think more object oriented. Here's another example: let's say our game engines rendering code needs to interface resource and input managers, so it can do it's job. You could make those singletons and do sth like ResourceManager.getInstance().getResource(name). Or you could create an application class (e.g. GameEngine) that has ResourceManager and InputManager as private members. Then have the GameEngine pass these as necessary to methods of the rendering code. Such as r.render(resourcemanager);.

    For singletons—can easily be accessed from anywhere, it's like a global variable, but there can only be one copy of it.

    Against singletons—many uses of singletons can be solved by encapsulating it within in a parent object and passing a member object to another member objects methods.

    Sometimes just using a stupid global variable is the right thing. Like using GOTO or a compounded (and/or) conditional statement instead of writing the same error handling code N times with copy and paste.


    Code smarter, not harder.

提交回复
热议问题