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("======= 原型模式结束 =======") }