The design pattern I understand (C ++ implementation) -- The flyweight Pattern)

Source: Internet
Author: User
Overview

Think about the WPS used to edit the document. Many texts in the document are repeated. We cannot create an independent space for every Chinese character that appears, which is too costly, the best way is to share the same part to minimize the number of objects to be created. This is the core of the meta-mode, that is, to use the sharing technology to effectively support a large number of fine-grained objects.

The key to enabling shared object sharing is to differentiate the internal state and external State ). The internal state is stored inside the object and does not change with the environment. Therefore, the status can be shared.

The external state changes with the environment and cannot be shared. The external status of the object must be saved by the client. After the object is created, the object must be uploaded to the object. The external status and internal status are independent of each other.

Class Diagram and example

Abstract flyweight)

It is the superclass of all the specific Metadata classes. Specify the public interfaces to be implemented for these classes, and the operations that require the exte state can be passed in through the parameters of the method. Abstract metadata-sharing interfaces make it possible to enjoy the metadata, but do not force sub-classes to share. Therefore, not all metadata-sharing objects can be shared.

Concreteflyweight)

The specific metadata class implements the interface specified by the abstract metadata class. If there is an inner state, it must provide storage space for the inner state. The inherent state of the object must be unrelated to the environment of the object, so that the object can be shared in the system. Sometimes, a specific metadata class is called a simple metadata class, because a compound metadata class is composed of a specific metadata role.

Unsharableflyweight)

A metadata class that cannot be shared is also called a composite metadata class. A composite object is composed of multiple single-object objects that can be shared, but the composite object cannot be shared.

Flyweightfactoiy)

The Yuan factory class is responsible for creating and managing yuan objects. When a client object requests a metadata object, the metadata factory needs to check whether there is a qualified metadata object in the system. If yes, the meta-factory role should provide the existing meta-object. If the system does not have an appropriate meta-object, the meta-factory role should create a new appropriate meta-object.

Customer(Client)

The customer class needs to store the external status of all the object objects.

// Cplusplusflyweight. CPP: defines the entry point for the console application. // # include "stdafx. H "# include <iostream >#include <map> using namespace STD; class character {public: Virtual ~ Character () {}; virtual void setsize (INT, INT) = 0; virtual void display () = 0; protected: character () {}; char m_chsymbol; int m_nweight; int m_nheight;}; Class characloud: Public Character {public: characloud (); Virtual ~ Characloud (); void setsize (INT, INT); void display () ;}; characloud: characloud () {This-> m_chsymbol = 'a '; this-> m_nweight = 100; this-> m_nheight = 200;} characloud ::~ Characloud () {} void characloud: setsize (INT nweight, int nheight) {This-> m_nweight = nweight; this-> m_nheight = nheight;} void characloud: Display () {cout <"characloud:" <m_chsymbol <"(" <m_nweight <"," <m_nheight <")" <Endl;} class characterb: public Character {public: characterb (); Virtual ~ Characterb (); void setsize (INT, INT); void display () ;}; characterb: characterb () {This-> m_chsymbol = 'B '; this-> m_nweight = 100; this-> m_nheight = 200;} characterb ::~ Characterb () {} void characterb: setsize (INT nweight, int nheight) {This-> m_nweight = nweight; this-> m_nheight = nheight;} void characterb: Display () {cout <"characterb:" <m_chsymbol <"(" <m_nweight <"," <m_nheight <")" <Endl ;} class characterfactory {public: characterfactory (); Virtual ~ Characterfactory (); character * getcharacter (char); Private: STD: Map <char, character *> m_mchar;}; characterfactory: characterfactory () {m_mchar.insert (make_pair <char, character *> ('A', new characloud); m_mchar.insert (make_pair <char, character *> ('B', new characterb);} characterfactory ::~ Characterfactory () {} character * characterfactory: getcharacter (char chin) {Map <char, character * >:: iterator it = m_mchar.find (Chin); If (it! = M_mchar.end () {return (character *) IT-> second;} return NULL;} int _ tmain (INT argc, _ tchar * argv []) {characterfactory * pfactory = new characterfactory; // the internal state is stored inside the object and will not change character * character = pfactory-> getcharacter ('A') as the environment changes '); response-> display (); // The client saves character * CH2 = pfactory-> getcharacter ('B'); CH2-> setsize (500,800 ); CH2-> display (); Return 0 ;}

Key Points

1. Object-oriented solves the abstract problem, but as a program entity running on a machine, we need to consider the cost of the object. The flyweight design model mainly solves the problem of object-oriented cost, and generally does not touch the abstract problem of object-oriented.

2. flyweight uses Object sharing to reduce the number of objects in the system, thus reducing the memory pressure on the system caused by fine-grained objects. In specific implementation, you must pay attention to processing the object status.

3. The advantage of the metadata mode is that it greatly reduces the number of objects in the memory. However, it pays a very high price to achieve this: the Yuan-sharing model makes the system more complex. In order for objects to be shared, some States need to be externalized, which complicate the logic of the program. In addition, it externalizes the state of the object, and reads the external State to slightly extend the running time.

Applicability

When all of the following conditions are met, you can consider using the enjoy mode:

1. A system has a large number of objects.

2. These objects consume a large amount of memory.

3. Most of the statuses of these objects can be externalized.

4. These objects can be divided into many groups according to the inherent state. When the external object is removed from the object, each group can be replaced with only one object.

5. The software system does not depend on the identities of these objects. In other words, these objects can be undistinguished.

The system that meets the preceding conditions can use a shared object. Finally, you need to maintain a table that records all the existing metadata in the system in the metadata-sharing mode, which consumes resources. Therefore, the metadata mode should be used only when there are enough metadata instances available for sharing.

Advantages and disadvantages

The advantage of the Meta mode is that it greatly reduces the number of objects in the memory. However, it also pays a very high price to achieve this:

1. the metadata mode makes the system more complex. In order for objects to be shared, some States need to be externalized, which complicate the logic of the program.

2. the metadata mode externalizes the state of the object, while reading the external State leads to a slightly longer running time.

Lcl_data was originally created in csdn. Net [http://blog.csdn.net/lcl_data/article/details/8974679]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.