Dahua Design Patterns Twenty-Four Flyweight Patterns

Recently, a friend introduced some small outsourcing projects to Xiaocai, which is to make websites for some private owners. It started out as a product display website for a client. It took more than a week to complete it, and I also rented a virtual space for the client. Then, his other friends also hoped to make such a website, and then Xiaocai rented another space and uploaded a copy of the previous code. This seems to be a problem. Later, their friends all wanted Xiaocai to provide such a website, but the requirements were different. Some wanted it in the form of news releases, some in the form of blogs, and in the form of original product pictures and descriptions. The cost can be greatly reduced. However, renting a space per website is unlikely to reduce the cost. what can we do about it?

They are all similar business customers, and their requirements are information release, product display, blog messages, forums and other functions, and the requirements are not very different.

However, if another 100 companies make websites, do they have to apply for 100 spaces, use 100 databases, and then use similar code to replicate 100 times to achieve it? If this is the case, if there are bugs or new requirements changes, the maintenance volume is terrible.


If it is one instance per website, the code should be like this



That is to say, if you want to have three product displays and three blog websites, you need six website instances. In fact, they are all the same code in essence. If the number of websites increases, the number of instances will also increase. The resources of the server are wasted very seriously. Is there any way to solve this problem?

We can't share a set of codes for all websites, but after all, they are different websites with different data.

Why not share code? Now large blog sites, e-commerce sites, every blog or business in it can also be understood as a small site, but how do they do it?

Different user ID numbers are used to distinguish different users. The specific data and templates can be different, but the code core and database are shared.

First of all, for these enterprise customers, the website structure they need is very similar and they are not high-traffic websites. If they are divided into multiple virtual spaces for processing, it is equivalent to a lot of instance objects of the same website, which will cause a large number of servers. The waste of resources, of course, is actually the waste of banknotes. If it is integrated into a website to share its related code and data, then the hard disk, memory, CPU, database space and other server resources can be shared, reducing server resources, and For code, maintenance and extension are easier because it is an instance.



2. Flyweight Mode

Flyweight, which uses sharing technology to effectively support a large number of fine-grained objects.




FlyweightFactory returns an object that has already been generated according to customer needs, but in fact, it is not necessary to generate an instance of the object in advance.

Although shared objects are needed most of the time to reduce memory consumption, there may be occasions when shared objects are not needed, so the subclass of UnsharedConcreteFlyweight is necessary at this time, which can solve the problems that do not require shared objects.


3. Website sharing code

The website should have an abstract class and a concrete website class, and then generate objects through the website factory.





This basically realizes the shared object purpose of the Flyweight model, that is to say, no matter how many websites are built, as long as it is a 'product display', it is the same, as long as it is a 'blog', it is exactly the same, but there are some The problem is that the website built for a company is not a company, and their data will not be the same, so at least they should all have different accounts. In fact, this way of writing does not reflect the differences between the objects, only the parts they share.


4. Internal state and external state

The shared part inside the flyweight object that does not change with the change of the environment can be called the internal state of the flyweight object, and the state that changes with the change of the environment and cannot be shared is the external state.

The Flyweight pattern avoids the overhead of a large number of very similar classes. In programming, it is sometimes necessary to generate a large number of fine-grained class instances to represent data. It is sometimes possible to drastically reduce the number of classes that need to be instantiated if it can be found that these instances are basically the same except for the structural parameters. If you could move those parameters out of the class instance and pass them in at method invocation, you could drastically reduce the number of individual instances through sharing.

That is to say, the state required for the execution of Flyweight in Flyweight mode is either internal or external. The internal state is stored in the ConcreteFlyweigt object, while the external object should be stored or calculated by the client object. When calling Flyweight When the object operates, pass that state to it.

The customer's account is the external state and should be handled by a dedicated object.




In this way, the internal and external states can be coordinated. Due to the flyweight model, even if the requirements of 1,000 websites are received, as long as the requirements are the same or similar, your actual development code is also classified. The hard disk space, memory, and CPU resources are very small, which is indeed a good way.


5. Application of Flyweight Mode

If an application uses a large number of objects, and a large number of these objects cause a lot of storage overhead, it should be considered; there is most of the state of the object can be external state, if the external state of the object is deleted, then you can use When relatively few shared objects replace many groups of objects, flyweight can be considered.



The effect achieved by flyweight mode

Because the flyweight mode is used, the total number of instances is greatly reduced by the shared objects. The more objects are shared, the greater the storage savings, and the savings increases with the increase of the shared state.

In fact, in .NET, the string string uses the Flyweight pattern. The Object.ReferenceEquals(object objA, object objB) method is used to determine whether objA and objB are the same instance, and the return value is a bool value.


The return value is True, the two strings are the same instance.

If you need to create a new string object every time you create a string object, the memory overhead will be huge. So if the string object titleA is created for the first time, the next time the same string titleB is created, it just points its reference to the 'Dahua Design Pattern', thus realizing the sharing of the 'Dahua Design Pattern' in memory.

Although the flyweight pattern is more often a low-level design pattern, it also has applications in reality. For example, in the development of casual games, such as Go, Gobang, and Checkers, they all have a large number of chess pieces. What are their internal and external states?

Go and backgammon only have black and white colors, and checkers have slightly more colors, but they do not change much, so the color should be the internal state of the pieces, and the difference between the pieces is mainly the difference in position, so the azimuth coordinates should be the external state of the pieces. .

Like Go, a game of chess theoretically has 361 vacancies for placing pieces. If you use conventional object-oriented programming, there may be two or three hundred pieces objects generated in each game of chess, and it is difficult for one server to support more players. The home is playing the game of Go, after all, the memory space is still limited. If the Flyweight pattern is used to handle chess pieces, then the chess piece object can be reduced to only two instances. This is indeed a very good solution to the problem of object overhead.

In some cases, the number of objects may be too large, resulting in runtime resource and performance penalties. So how to avoid a large number of fine-grained objects without affecting the client program is a question worth thinking about. Flyweight mode can run the sharing technology to effectively support a large number of fine-grained objects. However, using the flyweight mode requires maintaining a list of all existing flyweights in the system, which itself requires resources, and the flyweight mode makes the system more complicated. To make objects sharable, some state needs to be externalized, which complicates the logic of the program. Therefore, Flyweight should only be worth using when there are enough object instances to share.




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325527421&siteId=291194637