The pattern of C + + design mode _c language

Source: Internet
Author: User
Tags getcolor server memory

Objective

Boring time, also go to the QQ Game Hall play Gobang or chess; As a programmer, see a product, always want to think about it is how to design, how to complete, I think this is all programmers will do things right (obsessive-compulsive disorder??????? )。 Sometimes, think over, but also to do a demo out, to reflect their NB, and then a little sense of achievement.

When playing Gobang or chess, I thought, how did Tencent's gang do it? Gobang's chess pieces have Black-and-white color, each time put a pawn on the new one object? Chess has a car, horse, phase, scholar, handsome, artillery and soldiers, is not every game to all the chess pieces are new out? If it is really the new one for each piece, then add so many people to play, how many objects to new Ah, if this is done, I think how many servers are uncertain, perhaps the QQ game Hall will be worse than 12306. So how did Tencent's gang come to realize it? That's about the pattern of the benefits we've summed up today.

What is the privilege mode?

In Gof's "design pattern: The basics of reusable object-oriented software" in the book, this is said: the use of shared technology to effectively support a large number of fine-grained objects.

As mentioned above, if each piece is a new object, there will be a large number of fine-grained pieces of objects, this server memory space is a test, but also a waste. We all know that, for example, I am in Room No. 2013 and others under the Gobang, No. 2014 rooms are also under Gobang, and not because I am in Room No. 2013, and others in Room No. 2014, and lead to our pieces are not the same. That is to say, Room No. 2013 and Room No. 2014 are the same pieces, all the Gobang rooms are the same pieces. The only difference is that each piece is in different places on different boards in different rooms. So, for the pieces, we do not have to put a piece on the new piece object, just need to request to get the corresponding pieces of the object, if not, on a new piece object, if there is, directly return the pawn object. Here to Gobang as an example, for analysis, when the player put the first white pieces on the board, at this time because there is no white pieces, so new a white pieces; when another player puts the first black piece, there is no black pawn, so a new black piece is needed. When the player again put a white piece, to inquire whether there are already existing white pieces object, because the first time has been new a white pawn object, so, now will not be new again a white piece object, but return to the previous new white piece object; for black pieces, it's the same thing. , we only need to set the different board positions of the pieces.

UML Class Diagram

Flyweight: Describes an interface through which Flyweight can be accepted and acting on the external state;

Concreteflyweight: Implements the flyweight interface, and for the definition of some internal state, the Concreteflyweight object must be shareable, and the state it stores must be internal; It must be independent of the scene of the Concreteflyweight object;

Unsharedconcreteflyweight: Not all of the flyweight subclasses need to be shared. The flyweight interface makes sharing possible, but it does not force sharing.

Flyweightfactory: Create and manage flyweight objects. It needs to ensure that flyweight is reasonably shared; When a user requests a flyweight, the Flyweightfactory object provides an instance that has already been created, and if the requested instance does not exist, a new instance is created;

Client: maintains a reference to flyweight, and it needs to compute or store the external state of the flyweight.

Implementation Essentials

According to our experience, when you want to share an object, you need to take into account the state of the object; When different clients get the shared object, they may modify some states of the shared object; Everyone modifies the state of the shared object, and then the object state is disturbed. For the privilege mode, it is important to consider the state of the shared object when implementing it. So how does the pattern of the privilege be achieved?

In the meta mode, there are two very important concepts: internal state and external state.

The internal state is stored in flyweight, which contains information that is independent of the flyweight scene, which allows flyweight to be shared. The external state depends on the flyweight scene and changes according to the scene, so it is not shared. The user object is responsible for passing the external state to the flyweight when necessary.

The state required for flyweight execution must be internal or external. The internal state is stored in the Concreteflyweight object, while the external object is stored or computed by the client object. When the user invokes the action of the flyweight object, the state is passed to it. At the same time, users should not instantiate the Concreteflyweight class directly, but only get Concreteflyweight objects from the Flyweightfactory object, which ensures that they are properly shared, because sharing an instance So when you create this instance, you can consider using a singleton pattern for implementation.

The factory class in the privilege mode maintains a list of instances, all shared instances are saved in this list, and when a user requests a shared object from a factory class in the meta mode, it first queries the instance table, creates one if no corresponding instance exists, and returns the corresponding instance directly if it exists.

Code implementation:

Copy Code code as follows:

#include <iostream>
#include <map>
#include <vector>
using namespace Std;

typedef struct POINTTAG
{
int x;
int y;

Pointtag () {}
Pointtag (int A, int b)
{
x = A;
y = b;
}

BOOL operator < (const pointtag& Other) const
{
if (x < other.x)
{
return true;
}
else if (x = = other.x)
{
Return y < Other.y;
}

return false;
}
}point;

typedef enum PIECECOLORTAG
{
Black,
White
}piececolor;

Class Cpiece
{
Public
Cpiece (piececolor color): M_color (color) {}
Piececolor GetColor () {return m_color;}

Set the external state
void SetPoint (Point point) {m_point = point;}
Point GetPoint () {return m_point;}

Protected
Internal State
Piececolor M_color;

External state
Point M_point;
};

Class Cgomoku:public Cpiece
{
Public
Cgomoku (piececolor color): cpiece (color) {}
};

Class Cpiecefactory
{
Public
Cpiece *getpiece (piececolor color)
{
Cpiece *ppiece = NULL;
if (M_vecpiece.empty ())
{
Ppiece = new Cgomoku (color);
M_vecpiece.push_back (ppiece);
}
Else
{
BOOL Bfound = false; Thank you very much for Fireace point.
For (vector<cpiece *>::iterator it = M_vecpiece.begin (); it!= m_vecpiece.end (); ++it)
{
if ((*it)->getcolor () = = color)
{
Bfound = true;
Ppiece = *it;
Break
}
Bfound = false;
}
if (!bfound)
{
Ppiece = new Cgomoku (color);
M_vecpiece.push_back (ppiece);
}
}
return ppiece;
}

~cpiecefactory ()
{
For (vector<cpiece *>::iterator it = M_vecpiece.begin (); it!= m_vecpiece.end (); ++it)
{
if (*it!= NULL)
{
Delete *it;
*it = NULL;
}
}
}

Private
Vector<cpiece *> m_vecpiece;
};

Class Cchessboard
{
Public
void Draw (Cpiece *piece)
{
if (Piece->getcolor ())
{
cout<< "Draw a White" << "at (" <<piece->getpoint () .x<< "," <<piece->getpoint (). Y << ")" <<endl;
}
Else
{
cout<< "Draw a Black" << "at (" <<piece->getpoint () .x<< "," <<piece->getpoint (). Y << ")" <<endl;
}
M_mappieces.insert (Pair<point, Cpiece *> (Piece->getpoint (), piece));
}

void Showallpieces ()
{
For (Map<point, cpiece *>::iterator it = M_mappieces.begin (); it!= m_mappieces.end (); ++it)
{
if (It->second->getcolor ())
{
cout<< "(" <<it->first.x<< "," <<it->first.y<< ") has a white chese." <<endl;
}
Else
{
cout<< "(" <<it->first.x<< "," <<it->first.y<< ") has a black chese." <<endl;
}
}
}

Private
Map<point, cpiece *> m_mappieces;
};

int main ()
{
Cpiecefactory *ppiecefactory = new Cpiecefactory ();
Cchessboard *pcheseboard = new Cchessboard ();

The Player1 get a white piece from the pieces bowl
Cpiece *ppiece = ppiecefactory->getpiece (white);
Ppiece->setpoint (Point (2, 3));
Pcheseboard->draw (ppiece);

The Player2 get a black piece from the pieces bowl
Ppiece = Ppiecefactory->getpiece (black);
Ppiece->setpoint (Point (4, 5));
Pcheseboard->draw (ppiece);

The Player1 get a white piece from the pieces bowl
Ppiece = ppiecefactory->getpiece (white);
Ppiece->setpoint (Point (2, 4));
Pcheseboard->draw (ppiece);

The Player2 get a black piece from the pieces bowl
Ppiece = Ppiecefactory->getpiece (black);
Ppiece->setpoint (Point (3, 5));
Pcheseboard->draw (ppiece);

/*......*/

Show All Cheses
cout<< "Show All Cheses" <<endl;
Pcheseboard->showallpieces ();

if (Pcheseboard!= NULL)
{
Delete Pcheseboard;
Pcheseboard = NULL;
}
if (ppiecefactory!= NULL)
{
Delete ppiecefactory;
Ppiecefactory = NULL;
}
}

The internal state includes the color of the pieces, and the external state includes the position of the pieces on the board. Finally, we save more than one instance object to store the space of the piece color, thus achieving the space saving.

In the code above, I set up a ccheseboard to represent the chessboard, where the black and white pieces are preserved, which is equivalent to preserving the external state of the shared object externally, and to the Checkerboard object, can we use the pattern of the element? Then design a chess game class to manage chess pieces on the board layout, to save the external state. For this, there is no discussion here.

Advantages

The privilege pattern avoids the overhead of a large number of very similar objects. In programming, it is sometimes necessary to generate a large number of fine-grained class instances to represent data. If you can find that these instance data are basically the same except for a few parameters, you can drastically reduce the number of objects by using the pattern.

Use occasion

The effectiveness of the flyweight pattern depends largely on how it is used and where it is used. When the following conditions are met, we can use the privilege mode.

1. An application uses a large number of objects;
2. Due to the use of a large number of objects, resulting in a large storage overhead;
3. Most States of objects can become external states;
4. If you delete the external state of an object, you can replace many groups of objects with a relatively small number of shared objects.

Extended

Before summing up the combination mode combination mode, now look back, enjoy the meta mode is like in the combination of the model based on a factory class, to share control. Yes, the combination mode sometimes produces a lot of fine-grained objects, and in many cases we use the meta pattern and the combination pattern together.

Summarize

The use of the meta pattern can avoid the overhead of a large number of similar objects and reduce space consumption, and space consumption is determined by the following factors:

1. Reduction in the number of instance objects;
2. The number of internal states of objects; the more internal state of an object, the less space it consumes;
3. Whether the external state is calculated or stored, because the external state may require storage, and if the external state is stored, there will not be much space savings.

The more flyweight you share, the more savings you save, and the amount of savings that grows with the increase in shared state. When an object uses a large number of internal and external States, and the external state is computed rather than stored, the amount of savings will be maximized. So there are two ways to save storage: Use sharing to reduce internal state consumption, and compute time in exchange for storage of external states.

At the same time, in the implementation, we must control the external state and the corresponding relationship between the shared objects, such as I in the Code implementation section, in the Ccheseboard class using a map to map to each other, this mapping in the actual development needs to consider.

Well, the pattern of the privilege is summed up here. I hope you and I share your understanding of the design pattern. I firmly believe that: sharing makes us more progress.
PS: As for Tencent, the gang is how to realize the QQ game Hall, I do not know, here is also completely guessing, please do not use this as a benchmark.

Related Article

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.