The share mode is mainly used to reuse objects and save memory. There are two prerequisites for using the share mode:

  1. A meta-object is immutable: after a meta-schema is created, its variables and properties do not change

  2. A large number of duplicate objects exist in the system: These duplicate objects can use the same share and only have one copy in the memory, which saves a lot of space. Of course, this is also why the meta-object is immutable, because there are many references and changes can cause problems.

UML class diagrams location: www.processon.com/diagraming/…

This article is linked to: github.com/shidawuhen/…

Definition 1.

1.1 Share Mode

Share pattern: Use sharing technology to efficiently support a large number of fine-grained objects.

UML:

1.2 analysis

The sharing mode is to abstract out the common and invariable objects in the system to achieve the effect of sharing.

The abstract object interface is Flyweight, and the ConcreteFlyweight is the actual shared object. UnsharedConcreteFlyweight exists, mainly to see if there is object without sharing.

The factory FlyweightFactory is included in the share mode, mainly because although the share structure required in the system is determined, the attributes of the share are different, so multiple objects need to be managed. The factory mode is used here. For details on factory patterns, see the article Go Design Patterns (7)- Factory Patterns.

2. Application scenarios

Enjoy yuan mode or there are a lot of specific use scenarios, such as a lot of network type chess and card games. Assuming that there are 100W chess games going on at the same time, the system needs to maintain 32* 100W chess objects without using the free mode. But the text, color and rules of chess remain the same, only the holders and positions change. Therefore, abstracting 32 chess objects and using them as free elements can greatly save space without increasing costs.

The meta pattern is not so much a design pattern as a design concept, mainly about the abstract ability to extract the same module for different modules to use. From this dimension, extracting the same functionality, singleton patterns, and so on from code refactoring is another privilege.

3. Code implementation

Write about chess management in a chess game.

package main

import "fmt"

/** * @author: Jason Pang * @description: Chess class, with text, color, rules, these three impermanent attributes */
type Piece struct {
   text  string
   color string
   rule  string
}

/** * @author: Jason Pang * @description: Pawn information * @Receiver p * @return string */
func (p *Piece) String(a) string {
   return fmt.Sprintf("%s, color %s, rule %s", p.text, p.color, p.rule)
}

/** * @author: Jason Pang * @description: Chess position */
type Pos struct {
   x int64
   y int64
}

/** * @author: Jason Pang * @description: A piece in the game */
type GamePiece struct {
   piece   *Piece // Pawn pointer
   pos     Pos    // Chess position
   ownerId int64  / / player ID
   roomId  int64  / / the room ID
}

/** * @author: Jason Pang * @description: Chess pieces in the game * @receiver g * @return string */
func (g *GamePiece) String(a) string {
   return fmt.Sprintf("%s position is (%d,%d)", g.piece, g.pos.x, g.pos.y)
}

/** * @author: Jason Pang * @description: Chess factory, containing 32 pieces of information */
type PieceFactory struct {
   pieces []*Piece
}

/** * @author: Jason Pang * @description: Create a chess piece. The information of the pieces is unchanged * @receiver f */
func (f *PieceFactory) CreatePieces(a) {
   f.pieces = make([]*Piece, 32)
   f.pieces[0] = &Piece{
      text:  "Soldier",
      color: "Red",
      rule:  "You can only advance one step before crossing the river, and then you can only move one step or left or right.",
   }
   f.pieces[1] = &Piece{
      text:  "Soldier",
      color: "Black",
      rule:  "You can only advance one step before crossing the river, and then you can only move one step or left or right.",}//todo creates other pieces. Here you can create a configuration file to make it easier. A rule engine can be set up in the system to control the chess movement.
}

/** * @author: Jason Pang * @description: Obtain pawn information * @receiver f * @param ID * @return *Piece */
func (f *PieceFactory) GetPiece(id int64) *Piece {
   return f.pieces[id]
}

/** * @author: Jason Pang * @description: Initializes the board * @param roomId * @param U1 * @param u2 */
func InitBoard(roomId int64, u1 int64, u2 int64, factory *PieceFactory) {
   fmt.Printf("Create room %d, players are %d and %d \n", roomId, u1, u2)
   fmt.Println("Initialize the board")

   fmt.Printf("Player % D's pieces are \n", u1)
   piece := &GamePiece{
      piece:   factory.GetPiece(0),
      pos:     Pos{1.1},
      roomId:  roomId,
      ownerId: u1,
   }
   fmt.Println(piece)

   fmt.Printf("Player % D's pieces are \n", u2)
   piece2 := &GamePiece{
      piece:   factory.GetPiece(1),
      pos:     Pos{16.1},
      roomId:  roomId,
      ownerId: u2,
   }
   fmt.Println(piece2)
}
func main(a) {
   factory := &PieceFactory{}
   factory.CreatePieces()
   InitBoard(1.66.88, factory)
}
Copy the code

Output:

➜ myproject go run main.go

Create room 1 for players 66 and 88

Initializing the board

Player 66’s piece is

The pawn, which is red, can only advance step by step before crossing the river, and can only advance step by step after crossing the river or move left and right is (1,1).

Player 88’s pieces are

The pawn is black and can only advance one step before crossing the river and one step after crossing the river or move left or right is (16,1).

3 summary

Enjoy yuan model fully illustrates the importance of abstraction, I hope you can use this model to optimize the system.

The last

If you like my article, you can follow my public account (Programmer Malatang)

My personal blog is shidawuhen.github. IO /

Review of previous articles:

recruitment

  1. Bytes to beat | push big 24:00

  2. Bytes to beat | headlines today guangzhou server push r&d engineers

  3. Bytes to beat | trill electricity now hiring front-end development project in Shanghai

  4. Bytes to beat | trill electricity senior server-side development engineer – trading in Shanghai

  5. Bytes to beat | trill electric ShangWuHan server-side development engineer (senior)

  6. Bytes to beat | fly book big customer push product manager

  7. Bytes to beat | trill electricity service side technical posts vacant

  8. Bytedance recruitment special

Design patterns

  1. Go Design Mode (16)- Composite mode

  2. Go Design Mode (15)- Facade mode

  3. Go Design Pattern (14)- Adapter pattern

  4. Go Design Mode (13)- Decorator mode

  5. Go Design Mode (12)- Bridge mode

  6. Go Design Pattern (11)- Proxy pattern

  7. Go Design Mode (10)- Prototype mode

  8. Go Design Mode (9)- Builder mode

  9. Go Design Pattern (8)- Abstract Factory

  10. Go Design Mode (7)- Factory Mode

  11. Go Design Pattern (6)- Singleton pattern

  12. Go Design Pattern (5)- Class diagram symbolic representation

  13. Go Design Pattern (4)- Code writing optimization

  14. Go Design Pattern (4)- Code writing

  15. Go Design Patterns (3)- Design principles

  16. Go Design Pattern (2)- Object-oriented analysis and design

  17. Go Design Pattern (1)- Syntax

language

  1. No more fear of not getting Gin request data

  2. Understand pprof

  3. Go tool generate

  4. Go singleton implementation scheme

  5. Implementation principle of Go channel

  6. Implementation principle of Go timer

  7. Beego framework use

  8. Golang source BUG tracking

  9. Gin framework concise version

  10. Gin source code analysis

architecture

  1. The paging check pit is designed

  2. Payment access general issues

  3. Current limiting 2

  4. Seconds kill system

  5. Distributed systems and consistency protocols

  6. Service framework and registry for microservices

  7. Discussion on Micro-service

  8. Current limiting implementation 1

  9. CDN request process details

  10. Common Cache tips

  11. How to effectively connect with third-party payment

  12. Algorithm is summarized

storage

  1. MySQL database sub-database sub-table

  2. MySQL development specification

  3. Redis implements distributed locking

  4. The implementation principle of atomicity, consistency and persistence of transactions

  5. InnoDB locks and transactions

network

  1. HTTP2.0 basics tutorial

  2. HTTPS Configuration Combat

  3. HTTPS Connection Process

  4. TCP Performance Optimization

tool

  1. GoLand Practical skills

  2. Automatically generate go struct from mysql table

  3. Markdown editor recommends – Typora

Reading notes

  1. Selected by MAO

  2. The principle of

  3. History As A Mirror

  4. Agile revolution

  5. How to exercise your memory

  6. Simple Logic – After reading

  7. Hot Wind – After reading

  8. Analects of Confucius – After reading

  9. Sun Tzu’s Art of War – Reflections from reading

thinking

  1. A little review of the past

  2. Some thoughts on blogging

  3. The experience of calling 119 at night

  4. Struggle to mobilize all forces for victory

  5. Anti-liberalism

  6. practical

  7. The standard by which you judge yourself

  8. 2020 Blog Summary

  9. Service team holiday shift plan

  10. Project process management

  11. Some thoughts on project management

  12. Some thoughts on product manager

  13. Thinking about programmer career development

  14. Thinking about code review