型模式

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

内容简介:原型(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)
}

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

查看所有标签

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

构建高性能Web站点

构建高性能Web站点

郭欣 / 电子工业出版社 / 2009-8 / 59.00元

本书围绕如何构建高性能Web站点,从多个方面、多个角度进行了全面的阐述,涵盖了Web站点性能优化的几乎所有内容,包括数据的网络传输、服务器并发处理能力、动态网页缓存、动态网页静态化、应用层数据缓存、分布式缓存、Web服务器缓存、反向代理缓存、脚本解释速度、页面组件分离、浏览器本地缓存、浏览器并发请求、文件的分发、数据库I/O优化、数据库访问、数据库分布式设计、负载均衡、分布式文件系统、性能监控等。......一起来看看 《构建高性能Web站点》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具