型模式

简书帅气的昵称已被使用 · · 1042 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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

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


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

模式的结构

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

模型的实现

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

//具体原型类
class Realizetype implements Clineable
{
        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)
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:简书帅气的昵称已被使用

查看原文:型模式

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1042 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传