Go设计模式之Prototype
原型模式(Prototype Pattern)
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
//例
package pattern
import (
"fmt"
"reflect"
)
//创建一个clonable抽象接口
type Cloneable interface {
Clone() interface{}
}
type Context struct {
}
//方法
func (this *Context) Clone() interface{} {
new_obj := (*this)
return &new_obj
}
//结构体基本信息
func (this *Context) string(typ interface{}) (str string) {
v := reflect.ValueOf(typ).Elem()
str += "Type:" + v.Type().Name() + "\n"
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
str += fmt.Sprintf("index %d: %s %s = %v\n", i,
v.Type().Field(i).Name, f.Type(), f.Interface())
}
return
}
type Context1 struct {
Uri string
Context
}
func (this *Context1) SetUri(uri string) {
this.Uri = uri
}
func (this *Context1) String() (str string) {
return this.string(this)
}
type Context2 struct {
Context
Echo string
}
func (this *Context2) SetEcho(echo string) {
this.Echo = echo
}
func (this *Context2) String() (str string) {
return this.string(this)
}
type ContextPool map[string]*Context
func (this *ContextPool) AddContext(key string, val *Context) {
(*this)[key] = val
}
func (this *ContextPool) GetContext(key string) *Context {
val, ok := (*this)[key]
if ok {
return val.Clone().(*Context)
}
return nil
}
本质特点:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
2017年12月27日23:44:28 小路·写·设计篇

浙公网安备 33010602011771号