File tree 3 files changed +76
-1
lines changed
3 files changed +76
-1
lines changed Original file line number Diff line number Diff line change
1
+ package flyweight
2
+
3
+ var units = map [int ]* ChessPieceUnit {
4
+ 1 : {
5
+ ID : 1 ,
6
+ Name : "車" ,
7
+ Color : "red" ,
8
+ },
9
+ 2 : {
10
+ ID : 2 ,
11
+ Name : "炮" ,
12
+ Color : "red" ,
13
+ },
14
+ // ... 其他棋子
15
+ }
16
+
17
+ // ChessPieceUnit 棋子享元
18
+ type ChessPieceUnit struct {
19
+ ID uint
20
+ Name string
21
+ Color string
22
+ }
23
+
24
+ // NewChessPieceUnit 工厂
25
+ func NewChessPieceUnit (id int ) * ChessPieceUnit {
26
+ return units [id ]
27
+ }
28
+
29
+ // ChessPiece 棋子
30
+ type ChessPiece struct {
31
+ Unit * ChessPieceUnit
32
+ X int
33
+ Y int
34
+ }
35
+
36
+ // ChessBoard 棋局
37
+ type ChessBoard struct {
38
+ chessPieces map [int ]* ChessPiece
39
+ }
40
+
41
+ // NewChessBoard 初始化棋盘
42
+ func NewChessBoard () * ChessBoard {
43
+ board := & ChessBoard {chessPieces : map [int ]* ChessPiece {}}
44
+ for id := range units {
45
+ board .chessPieces [id ] = & ChessPiece {
46
+ Unit : NewChessPieceUnit (id ),
47
+ X : 0 ,
48
+ Y : 0 ,
49
+ }
50
+ }
51
+ return board
52
+ }
53
+
54
+ // Move 移动棋子
55
+ func (c * ChessBoard ) Move (id , x , y int ) {
56
+ c .chessPieces [id ].X = x
57
+ c .chessPieces [id ].Y = y
58
+ }
Original file line number Diff line number Diff line change
1
+ package flyweight
2
+
3
+ import (
4
+ "testing"
5
+
6
+ "github.com/stretchr/testify/assert"
7
+ )
8
+
9
+ func TestNewChessBoard (t * testing.T ) {
10
+ board1 := NewChessBoard ()
11
+ board1 .Move (1 , 1 , 2 )
12
+ board2 := NewChessBoard ()
13
+ board2 .Move (2 , 2 , 3 )
14
+
15
+ assert .Equal (t , board1 .chessPieces [1 ].Unit , board2 .chessPieces [1 ].Unit )
16
+ assert .Equal (t , board1 .chessPieces [2 ].Unit , board2 .chessPieces [2 ].Unit )
17
+ }
Original file line number Diff line number Diff line change @@ -43,7 +43,7 @@ go 设计模式实现,包含 23 种常见的设计模式实现
43
43
44
44
- [ 门面模式(Facade Design Pattern)] ( ./09_facade ) [ ![ ] ( https://img.shields.io/badge/BLOG-%E7%82%B9%E5%87%BB%E6%9F%A5%E7%9C%8B-success?style=flat&cacheSeconds=360000 )] ( https://lailin.xyz/post/facade.html )
45
45
- [ 组合模式(Composite Design Pattern)] ( ./10_composite ) [ ![ ] ( https://img.shields.io/badge/BLOG-%E7%82%B9%E5%87%BB%E6%9F%A5%E7%9C%8B-success?style=flat&cacheSeconds=360000 )] ( https://lailin.xyz/post/composite.html )
46
- - 享元模式
46
+ - [ 享元模式(Flyweight Design Pattern) ] ( ./11_flyweight ) [ ![ ] ( https://img.shields.io/badge/BLOG-%E7%82%B9%E5%87%BB%E6%9F%A5%E7%9C%8B-success?style=flat&cacheSeconds=360000 )] ( https://lailin.xyz/post/flyweight.html )
47
47
48
48
## 行为型模式
49
49
You can’t perform that action at this time.
0 commit comments