The two pattern seems to achieve the same thing. What are the different use cases in real world? Thanks
A singleton is usually used to represent objects there is only one of, such as a keyboard, the computer screen, main memory. It could represent more abstract things like a messaging dispatch centre or coordinator. A database link for your whole application.
You could think of both a Singleton and a Flyweight as having a factory producing an object. A key difference is that the Singleton factory always returns the same object. A Flyweight factory in contrast is parameterized. The creation function takes an argument. Depending on the value of the argument a different Flyweight object will be returned.
You may have a singleton representing the current page being worked on in a word processor. The individual characters on the page however may be represented as Flyweights.
The similarity with a singleton here is that each occurrence of the character 'A' will refer to the same object. So giving 'A' as a parameter to the Flyweight factory will always return the same object. Hence there is a a singleton like behavior in that every time you create an 'A' object you get the same object returned.
The distinction from a Singleton factory is that the Flyweight factory allows a whole class of related objects to be created.
A Singleton is often mutable. However with Flyweights we tend to keep mutable state outside of the Flyweight. So e.g. if we have flyweight objects representing characters in a document, then the character position would typically be stored separate from the Flyweight object.
While I don't rule it out, I cannot think of any case where you would want to make the Flyweight object itself mutable. Imagine you have a Flyweight representing the character 'B' and then you change it to 'A'. Then 'B' in your document would change to 'A'. That would be highly undesirable.
Likewise if Flyweights represent color. It would confusing if you created a red color and it was green instead because its underlying flyweight object was changed to green somewhere else in the code.
Examples from Cocoa (Objective-C):
UIApplication.sharedApplication.statusBarHidden = YES
This is obviously a single object and you can change its state.
UIColor *red = [UIColor redColor]
In this case it is not obvious if we get a new object each time or not. Because colors are immutable, the maintainers of this API are free to implement common colors such as red, blue, green, yellow and gray as Flyweight objects. That means there is a pool of common objects which get reused when you call the constructor.
To the user it makes no difference whether a flyweight pattern is used behind the scenes or not. This is a reason why I will claim that immutability is a desirable property for flyweight objects.
Also note how parameterization is implicit in this case. You pick color, by using different named constructors. yellowColor
, blueColor
etc.