-
Notifications
You must be signed in to change notification settings - Fork 347
/
Copy pathflyweight.go
58 lines (51 loc) · 947 Bytes
/
flyweight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package flyweight
var units = map[int]*ChessPieceUnit{
1: {
ID: 1,
Name: "車",
Color: "red",
},
2: {
ID: 2,
Name: "炮",
Color: "red",
},
// ... 其他棋子
}
// ChessPieceUnit 棋子享元
type ChessPieceUnit struct {
ID uint
Name string
Color string
}
// NewChessPieceUnit 工厂
func NewChessPieceUnit(id int) *ChessPieceUnit {
return units[id]
}
// ChessPiece 棋子
type ChessPiece struct {
Unit *ChessPieceUnit
X int
Y int
}
// ChessBoard 棋局
type ChessBoard struct {
chessPieces map[int]*ChessPiece
}
// NewChessBoard 初始化棋盘
func NewChessBoard() *ChessBoard {
board := &ChessBoard{chessPieces: map[int]*ChessPiece{}}
for id := range units {
board.chessPieces[id] = &ChessPiece{
Unit: NewChessPieceUnit(id),
X: 0,
Y: 0,
}
}
return board
}
// Move 移动棋子
func (c *ChessBoard) Move(id, x, y int) {
c.chessPieces[id].X = x
c.chessPieces[id].Y = y
}