型模式

栏目: 后端 · 发布时间: 6年前

内容简介:原型(Prototype)模式:用一个已经创建的实例作为原型,通过复制原型对象来创建一个和原型相同或相似的新对象原型模式的克隆分为浅克隆和深克隆

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

原型(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)
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Ajax基础教程

Ajax基础教程

(美)阿斯利森、(美)舒塔、金灵 / 金灵 / 人民邮电出版社 / 2006-02-01 / 35.00元

Ajax技术可以提供高度交互的Web应用,给予用户更丰富的页面浏览体验。本书重点介绍Ajax及相关的工具和技术,主要内容包括XMLHttpRequest对象及其属性和方法、发送请求和处理响应、构建完备的Ajax开发工具、使用JsUnit测试JavaScript、分析JavaScript调试工具和技术,以及Ajax开发模式和框架等。本书中所有例子的代码都可以从Apress网站本书主页的源代码(Sou......一起来看看 《Ajax基础教程》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具