来自一个大佬的博客,建议食用
设计模式不分语言,是一种思维层面的体现,但是不能在不同语言中使用同一套实现(每种语言有不同的特性),比如go,本身是没有继承一说,但是通过结构体的组合来实现语义上的继承。而多态也是通过接口的方式来实现的。
下方的图来自于大佬博客,贴在这里方便查看!!!
设计原则 设计模式 结构型模式 享元模式享元模式就是为了更好的节省和管理资源复用,属于对象级别(不可变对象)的复用。通常通过pool来缓存已创建的对象,用时取出,用完回收。
java的线程池以及数据库连接池都是享元模式。
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
}



