What to do when you know that only a single instance of a class will ever be instantiated - singleton, static, or plain old class?
There are cases when there is a class which has no inherent reason to be a singleton or static, yet it also doesn't make much sense in creating more than 1 instance of it.
The example I'm facing is a "header" object in a PHP page. It's a homebrew class which helps to manage CSS/JS scripts (prevents duplicate references and manages some dependencies) and renders a bunch of common tags in the header (meta content-type, title, script, link stylesheet, etc) It's a class used universally among all the views, simply to ease writing code.
Since a page only has one header, it makes little sense to have more than 1 instance of this class. On the other hand, 开发者_如何学Cmaking it static/singleton also seems like adding a limitation to it for which there is no reason.
This all comes down to who you're coding for and what the overall goal is. If you want to ensure that a header class can only have one instance, then writing it as a Singleton is necessary to ensure that it is only created once. However, if you don't want to limit it in such a way, then there is no point to write it as a singleton.
Your question answers itself. If you're coding something that will be used by others and it's functionality depends on there only being one instance, then code it as a singleton. If you want it to remain open and it does not affect the code functionality if there is more than one instance, then leave it as it is. If you're writing this for yourself, then it is up to you on how you want to use it.
To summarize. A singleton ENFORCES that only one instance is created. This should be used only when it is important to never have more than one instance of your class.
精彩评论