原型模式 (Prototype Pattern),主要用于通过 克隆现有对象 来创建新对象,避免重复初始化对象的开销。下面是示例代码:
package main
import "fmt"
// Prototype 原型接口
type Prototype interface {
Clone() Prototype
}
// ConcretePrototype 具体原型
type ConcretePrototype struct {
Name string
Age int
}
func (p *ConcretePrototype) Clone() Prototype {
// 创建一个新对象,并复制当前对象的属性
return &ConcretePrototype{
Name: p.Name,
Age: p.Age,
}
}
func (p *ConcretePrototype) String() string {
return fmt.Sprintf("Name: %s, Age: %d", p.Name, p.Age)
}
func main() {
// 创建原型对象
prototype := &ConcretePrototype{
Name: "Alice",
Age: 25,
}
// 克隆原型对象
clone := prototype.Clone().(*ConcretePrototype)
// 修改克隆对象的属性
clone.Name = "Bob"
clone.Age = 30
// 输出原型对象和克隆对象
fmt.Println("Prototype:", prototype)
fmt.Println("Clone:", clone)
}
代码解析
- 核心结构定义
// 原型接口
type Prototype interface {
Clone() Prototype // 声明克隆方法
}
// 具体原型(需要被克隆的对象)
type ConcretePrototype struct {
Name string
Age int
}
- Prototype 接口:定义 Clone 方法规范,所有可克隆对象必须实现。
- ConcretePrototype:具体需要克隆的对象,包含 Name 和 Age 属性。
- 克隆方法实现
func (p *ConcretePrototype) Clone() Prototype {
return &ConcretePrototype{
Name: p.Name, // 复制字段值
Age: p.Age,
}
}
- 浅拷贝 (Shallow Copy):直接复制结构体的所有值类型字段。
- 接口实现:返回 Prototype 接口类型,支持多态。
- 客户端使用
func main() {
prototype := &ConcretePrototype{Name: "Alice", Age: 25} // 原对象
clone := prototype.Clone().(*ConcretePrototype) // 克隆对象
clone.Name = "Bob" // 修改克隆体
fmt.Println("Prototype:", prototype) // 输出: Name: Alice, Age: 25
fmt.Println("Clone:", clone) // 输出: Name: Bob, Age: 30
}
- 结果:克隆后的对象与原对象相互独立,修改互不影响。
核心设计思想
1.避免重复初始化
直接复制已有对象的状态,省去构造参数传递和初始化逻辑。
2.动态配置对象
基于模板对象快速生成变体(如游戏中的 NPC 角色批量生成)。
3.解耦客户端与具体类
客户端只需依赖 Prototype 接口,无需知道具体克隆实现。
扩展使用场景
场景 1:游戏角色生成
// 怪物原型
type Monster struct {
Health int
Attack int
Skills []string
}
func (m *Monster) Clone() Prototype {
// 深拷贝 Skills 切片
skills := make([]string, len(m.Skills))
copy(skills, m.Skills)
return &Monster{
Health: m.Health,
Attack: m.Attack,
Skills: skills,
}
}
// 用法:批量生成不同属性的怪物
boss := &Monster{Health: 1000, Attack: 200, Skills: []string{"Fireball", "Charge"}}
minion1 := boss.Clone().(*Monster)
minion1.Health = 100 // 生成小怪
场景 2:文档模板克隆
type Document struct {
Content string
Format map[string]string // 样式配置
}
func (d *Document) Clone() Prototype {
// 深拷贝 map
format := make(map[string]string)
for k, v := range d.Format {
format[k] = v
}
return &Document{
Content: d.Content,
Format: format,
}
}
// 用法:基于模板创建新文档
template := &Document{
Content: "Default Template",
Format: map[string]string{"font": "Arial", "size": "12pt"},
}
report := template.Clone().(*Document)
report.Content = "Q4 Financial Report" // 复用格式
场景 3:配置对象多版本
type ServerConfig struct {
IP string
Port int
Settings map[string]interface{}
}
func (c *ServerConfig) Clone() Prototype {
// 深拷贝嵌套结构
settings := make(map[string]interface{})
for k, v := range c.Settings {
settings[k] = v
}
return &ServerConfig{
IP: c.IP,
Port: c.Port,
Settings: settings,
}
}
// 用法:生成测试环境配置
prodConfig := &ServerConfig{
IP: "192.168.1.1",
Port: 8080,
Settings: map[string]interface{}{
"cache": true,
"ssl": true,
},
}
testConfig := prodConfig.Clone().(*ServerConfig)
testConfig.IP = "127.0.0.1" // 修改为本地环境
testConfig.Settings["ssl"] = false // 关闭 SSL
深拷贝与浅拷贝问题
- 当前代码问题:原示例中的 ConcretePrototype 只有值类型字段,浅拷贝足够。但如果包含 引用类型(如切片、map、指针),需要实现深拷贝。
- 改进方案:
func (p *ConcretePrototype) Clone() Prototype {
// 假设 ConcretePrototype 包含引用类型字段 Data []int
dataCopy := make([]int, len(p.Data))
copy(dataCopy, p.Data)
return &ConcretePrototype{
Name: p.Name,
Age: p.Age,
Data: dataCopy, // 深拷贝切片
}
}
总结

通过原型模式,可以显著提升对象创建的灵活性和效率,尤其适合需要高频生成相似对象的系统。
2683

被折叠的 条评论
为什么被折叠?



