What are the practical use differences between Flyweight vs Singleton patterns?

后端 未结 7 474
攒了一身酷
攒了一身酷 2021-02-04 01:50

The two pattern seems to achieve the same thing. What are the different use cases in real world? Thanks

7条回答
  •  感情败类
    2021-02-04 02:39

    The flyweight structual pattern essentially removes duplication of objects needed to achieve a certain goal. For example, imagine you were typing an essay (or maybe a post on stack overflow), which is ultimately comprised of the same 26 letters in the (English) alphabet, repeated many times. Would it be more efficient to have 1000 separate objects each representing the letter 'E', or have one single object representing the letter 'E', referenced 1000 times? (Hint, it would generally be the latter)

    How the creation of each of the objects (ie. 26 letters) is implemented is a separate concern, however is commonly achieved with a factory method (a creational pattern) that utilizes "singleton like" characteristics.

    • Initialize an empty collection of characters.
    • Letter 'E' is needed?
    • If it already exists, retrieve that object from the collection, otherwise create a new letter 'E' and store it in the collection, to be re-used the next time.

    Is this done through a fully-fledged singleton object, or just a private variable that only the factory method can access? May or may not be. But either way, the singleton pattern is a creational pattern, describing ways to have only a single instance of an object in existence at any given point in time, and is not concerned with specific use cases such as "removing duplication of objects needed to achieve a certain goal".

提交回复
热议问题