内容简介:原型(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)
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 设计模式——订阅模式(观察者模式)
- 设计模式-简单工厂、工厂方法模式、抽象工厂模式
- java23种设计模式-门面模式(外观模式)
- 简单工厂模式、工厂模式、抽象工厂模式的解析-iOS
- Java 设计模式之工厂方法模式与抽象工厂模式
- JAVA设计模式之模板方法模式和建造者模式
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。