Golang and design pattern-Prototype prototype pattern

The Prototype prototype mode is actually a creational design mode that generates new instances based on the prototype of the instance. Enables you to copy objects, even complex objects, without making your code dependent on the class they belong to.

A typical application is dependency injection, which should be familiar to those who have done .Net and Java development. go also has a dependency injection framework

Scenes

The scene in this issue is very simple. We have implemented a simple dependency injection model.

Basic Types and Interfaces

This is the prototype interface, and instances that need to implement dependency injection must implement this interface

// 产品接口(原型接口)
type Product interface {
	// 用于演示的方法
	Use()
	// 克隆方法,返回自身的副本(不是指针)
	Clone() Product
}

Prototype pool management

There is a Map inside the Manager, and the registered instances are stored in the Map, and the methods of registering Register() and obtaining the instance of the prototype are provided Clone()

// 产品管理
type Manager struct {
	// 原型池
	products map[string]Product
}

// 注册原型到原型池
func (m *Manager) Register(name string, product Product) {
	_, ok := m.products[name]
	if ok {
		return
	}

	m.products[name] = product
}

// Clone一个对象,返回其副本
func (m *Manager) Clone(name string) Product {
	v, ok := m.products[name]
	if !ok {
		return nil
	}

	// 调用被克隆对象自身的克隆方法
	return v.Clone()
}

accomplish

Defines an IPhone type that implements the prototype interface

// 演示产品,实现了原型接口
type IPhone struct {
	Name string
}

// 演示方法
func (p *IPhone) Use() {
	fmt.Printf("正在使用 %s 打电话\n", p.Name)
}

// 克隆的细节
func (p *IPhone) Clone() Product {
	return &IPhone{Name: p.Name + "_clone"}
}

test

Here I judge that what Clone() returns is not the prototype itself by outputting the object pointer

func main() {
	iphone7 := IPhone{Name: "IPhone7"}
	iphone7.Use()
	fmt.Printf("%s 的指针式 %p \n\n", iphone7.Name, &iphone7)

	manager := Manager{products: make(map[string]Product)}
	manager.Register("iphone7", &iphone7)

	clone_iphone7 := manager.Clone("iphone7")
	clone_iphone7.Use()
	fmt.Printf("clone_iphone7 的指针式 %p \n", &clone_iphone7)
}

operation result

The result is as expected

 The code has been uploaded to Github: LyonNee/design_patterns_with_go: Golang-based design pattern code (github.com) 

Guess you like

Origin blog.csdn.net/Lyon_Nee/article/details/119619306