1
0
Fork 0
design-patterns/go/prototype/main.go

82 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
/*
实例
汤宝宝穿越到了星球大战世界,并掉到了克隆人军队的生产工厂。
ps
go中没有官方的深拷贝实现一些第三方库会使用reflect的方式来实现深拷贝但性能较差且不够类型安全。
比较安全的方法是逐步复制每个字段,会有稍许麻烦。
*/
import "fmt"
// 克隆人接口
type CloneTrooper interface {
clone() CloneTrooper
fight()
setid(id int)
}
// 具体的克隆人类
type CloneTrooperA struct {
Id int
}
func (c *CloneTrooperA) clone() CloneTrooper {
fmt.Printf("克隆人A-%d号正在克隆...\n", c.Id)
return &CloneTrooperA{Id: c.Id}
}
func (c *CloneTrooperA) fight() {
fmt.Printf("克隆人A-%d号准备战斗\n", c.Id)
}
func (c *CloneTrooperA) setid(id int) {
c.Id = id
}
type CloneTrooperB struct {
Id int
}
func (c *CloneTrooperB) clone() CloneTrooper {
fmt.Printf("克隆人B-%d号正在克隆...\n", c.Id)
return &CloneTrooperB{Id: c.Id}
}
func (c *CloneTrooperB) fight() {
fmt.Printf("克隆人B-%d号准备战斗\n", c.Id)
}
func (c *CloneTrooperB) setid(id int) {
c.Id = id
}
func main() {
fmt.Println("========= 原型模式 =========")
// 创建克隆人A原型
prototypeA := &CloneTrooperA{Id: 0}
prototypeA.fight()
cloneA1 := prototypeA.clone()
cloneA1.setid(1)
cloneA1.fight()
cloneA2 := cloneA1.clone()
cloneA2.setid(2)
cloneA2.fight()
// 创建克隆人B原型
prototypeB := &CloneTrooperB{Id: 0}
prototypeB.fight()
cloneB1 := prototypeB.clone()
cloneB1.setid(1)
cloneB1.fight()
cloneB2 := cloneB1.clone()
cloneB2.setid(2)
cloneB2.fight()
fmt.Println()
fmt.Println("======= 原型模式结束 =======")
}