原型模式

一、原型模式的定义与特点

原型(Prototype)模式:用一个已经创建的实例作为原型,通过复制原型对象来创建一个和原型相同或相似的新对象


二、原型模式的结构与实现

模式的结构

  • 抽象原型类: 规定了具体原型对象必须实现的接口
  • 具体原型类:实现抽象原型类的clone()方法,它是可被复制的对象
  • 访问类:使用具体原型类中的clone()方法来复制新的对象

模型的实现

原型模式的克隆分为浅克隆和深克隆

//具体原型类
class Realizetype implements Cloneable
{
        Realizetype()
        {
                System.out.println("具体原型创建成功!");
        }

        public Object clone() throw CloneNotSuppportedException
        {
                System.out.println("具体原型复制成功!")
                return (Realizetype)supper.clone();
        }
}

//原型模式的测试类
public class PrototypeTest
{
        public static void main(String[] args)throws CloneNotSupportedException
        {
                Realizetype obj1 = new Realizetype();
                Realizetype obj2 = (Realizetype)obj1.clone();
                System.out.println("obj1==obj2?"+(obj1==obj2));
        }
}

三、Golang实现原型模式

package prototype

//Cloneable 是原型对象需要实现的接口
type Cloneable interface{
      Clone()   Cloneable
}
    
type PrototypeManager struct {
        prototypes map[string]Cloneable
}

func NewPrototypeManager() *PrototypeManager {
        return &PrototypeManager{
                prototypes: make(map[string]Cloneable),
        }
}

func (p *PrototypeManager) Get(name string) Cloneable {
        return p.prototypes[name]
}

func (p *PrototypeManager) Set(name string, prototype Cloneable) {
        p.prototypes[name] = prototype
}

测试用例

package prototype

import "testing"

var manager *PrototypeManager

type Type1 struct {
        name string
}

func (t *Type1) Clone() Cloneable {
        tc := *t
        return &tc
}

func TestClone(t *testing.T) {
        t1 := manager.Get("t1")
      
        t2 := t1.Clone()

        if t1 == t2 {
                t.Fatal("error! get clone not working")
        }
}

func init() {
    manager := NewPrototypeManager()

    t1 := &Type1{
            name: "type1",
    }

    manager.Set("t1", t1)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容