Flyweight (Share mode)

Flyweight is a structural pattern, a design pattern for sharing objects.

Intent: Use sharing techniques to efficiently support a large number of fine-grained objects.

For example,

If you don’t understand the above description, it doesn’t matter. Design patterns need to be used in daily work. Examples will help you understand better.

The letter object of a rich text editor

Rich text editor In the English environment, the text consists of a large number of letters. In order to facilitate unified formatting and calculation, each letter needs to be stored as an object, but the cost of such storage is too high.

Given that there are 26 letters, there are a lot of letters that are reused in a document, and every letter is the same and read-only except for its location, is there a way to reduce the huge number of letter objects in rich text scenarios?

The cloud storage

When we upload a movie, sometimes tens of GIGABytes of content will be uploaded in less than a second. This is the web disk prompt you, “We have adopted extreme speed technology to transmit in seconds”. Will you be confused, why can’t such a powerful technology work every time?

In addition, when the web disk storage, the same movie may be stored in different users in different folders, and movie files are particularly huge, similar to rich text, movie files are only stored in different locations, and the rest of the content is particularly huge and read-only, what can be optimized storage?

Massively multiplayer games

In multiplayer games, the creation and calculation of common objects are done on the server in order to prevent hitouts, so how do you ensure that when one player picks up an item, another player sees an item that disappears?

In fact, this is self-evident, although game objects are independent from each other between different clients, in a game, all players’ objects are shared on the server.

Intention to explain

“Sharing” is the essence of the sharing mode, which uses a large number of objects with many internal states and few external states.

Intent: Use sharing techniques to efficiently support a large number of fine-grained objects.

The sharing technique can be understood as caching. Once an object is created, new objects are not created when the same object is accessed again. Instead, new objects are created and cached immediately when an object that has not been cached is accessed.

Doing this effectively supports a large number of fine-grained objects. In the rich text example, countless letters are a large number of fine-grained objects, in the web disk storage, a movie file is a large number of fine-grained objects, and in a massively multiplayer game, there are a large number of fine-grained objects per game.

These fine-grained objects all share the same characteristics:

  • It’s a huge amount. It’s easy to understand.
  • There is a large number of internal states that do not change from client to client.
    • Letters in rich text do not change as they are displayed in different statements, only in their state. Movie files will not change because they are placed in folders of different users. The only changes are which users belong to and which folders are placed in. In multiplayer games, the same weapon object does not have more ammo because there are multiple computers running independently, only which clients are accessed.
  • With little or no external state. As explained above, the position of the letter, the location of the movie, and the client of the gameobject are all external states, which are small in size compared to their internal states and can be easily stored separately.

In this case, we can save a lot of space by sharing the internal state of the object and storing the external state independently.

Especially for the web disk scenario, the user is promised 2 TB of storage space. When the user sees other people sharing 100 movies, he clicks “Download to my web disk”. At this time, 1 TB of his web disk space is occupied, but in fact, the web disk operator does not add 1 TB of storage space. It may actually add 1KB of storage space and record the storage location. This is where the web disk is a mess. It doesn’t take up space, but it takes up the storage space that the user actually bought.

Of course, this is the value of the yuan model, for the network disk company, the value is huge, for users, no value. So the value of the meta pattern is global, such as reducing the number of large letter objects for the whole rich text editor, but there is no optimization for each letter object.

chart

For clients, the following diagram describes how to share Flyweight:

  • Flyweight: Shared interface through which you can manipulate the external state of an object.
  • ConcreteFlyweight: Implements the Flyweight interface. This object is shareable.
  • UnsharedConcreteFlyweight: don’t be Shared object, because in the flyweight pattern, actually not all objects can be Shared.
  • FlyweightFactory: Creates and manages Flyweight objects. Flyweight objects returned by this Flyweight object are returned if they are already created, and a new Flyweight object is created if not.
  • Client: the Client that uses Flyweight.

It is clear from the second figure that two different clients hold the same aConcreteFlyweight reference.

The code example

The following example is written in typescript.

class FlyweightFactory {

  public getFlyWeight(key) {

    if (this.flyweight[key]) {

      return this.flyweight[key]

    }



    const flyweight = new Flyweight()

    this.flyweight[key] = flyweight

    return flyweight

  }

}

Copy the code

The flyweight factory provides a method called getFlyWeight, which actually caches flyweight instances by key. Only one flyweight instance is stored under the same key.

disadvantages

If there are not many fine-grained objects, there is no need to use the share pattern.

In addition, even if there are many fine-grained objects, if there is not much internal state of the object, and it is mainly external state, then the shared element pattern does not help, because by sharing objects, the shared element pattern saves only internal state, not external state.

In addition, if the share pattern maps to a number of shared objects that are not orders of magnitude smaller than the original object, it doesn’t make much sense to use it. For example, the rich text editor, for English, a total of 26 letters, then the optimization ratio of 10,000 words is 10000:26, but for Chinese articles, the text instances themselves are many, maybe in 10,000 words, after the weight is removed, there are still 3000 Chinese characters. Then the optimization ratio is 10000:3000, at this time the meaning of the yuan model is not so dozen.

conclusion

The essence of the share mode is to share objects as much as possible, which is especially suitable for scenarios where there are a large number of fine-grained objects with a large number of internal states and a small number of external states.

For cloud storage, the meta-share mode is a must because the cloud storage scenario requires a large number of fine-grained file objects and a large number of read-only files, which are ideal for sharing an object and each user stores only references.

The discussion address is: Close reading Design Patterns – Flyweight Yuan Patterns · Issue #290 · dT-fe /weekly

If you’d like to participate in the discussion, pleaseClick here to, with a new theme every week, released on weekends or Mondays. Front end Intensive Reading – Helps you filter the right content.

Pay attention to the front end of intensive reading wechat public account

Copyright Notice: Freely reproduced – Non-commercial – Non-derivative – Remain signed (Creative Commons 3.0 License)