Introduction to shared mode / shared meta mode (flyweight mode) of Java design pattern

Flyweight definition: avoid the overhead of a large number of small classes with the same content (such as memory consumption), so that everyone can share a class (metaclass).

Why use shared mode / shared meta mode

The principle of object-oriented language is that everything is an object, but if it is really used, sometimes the number of objects may appear very large. For example, if word processing software takes each word as an object, thousands of words, and the number of objects is thousands, which undoubtedly consumes memory, then we still need to "seek common ground while reserving differences" to find out the common ground of these object groups, Design a metaclass to encapsulate classes that can be shared. In addition, some features depend on the application context and are not shared. This is also divided into two important concepts in flyweight: internal state and external state.

To put it bluntly, first pinch an original model, and then generate specific models with different characteristics according to different occasions and environments. Obviously, different new objects need to be generated here, so factory mode often appears in flyweight mode. Flyweight's internal state is shared. Flyweight factory is responsible for maintaining a flyweight pool (pattern pool) to store objects in internal state.

Flyweight mode is a mode to improve program efficiency and performance, which will greatly speed up the running speed of the program. There are many applications: for example, if you want to read a series of strings from a database, many of these strings are repeated, then we can store these strings in the flyweight pool.

How to use sharing mode / meta mode

Let's start with the flyweight abstract interface:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>