设计模式之---原型模式

in #steemit7 years ago


原型模式(Prototype Pattern)

定义

Specify the kinds of objects to create using a prototypicalinstance, and create new objects by copying this prototype.
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
类图:
从类图可以看到原型模式的核心方法是clone,在jdk中内置Cloneable接口,只需实现Cloneable接口即可实现原型类

优点

  • 原型构造对象的效率要高于构造器构造对象的效率
  • 构造器中的初始化语句不用执行

缺点

  • 由于构造器中的语句不执行,如果处理不当,会出错

代码如下

public class PrototypeClass implements Cloneable{
    @Override
  protected PrototypeClass clone() throws CloneNotSupportedException {
        PrototypeClass prototypeClass=null;
 try {
            prototypeClass= (PrototypeClass) super.clone();
  }catch (CloneNotSupportedException e){
            e.printStackTrace();
  }

        return prototypeClass;
  }
}

测试代码

public class Test {
    public static void main(String[] args) {

        try {
            PrototypeClass prototypeClass=new PrototypeClass();
  PrototypeClass prototypeClass1=prototypeClass.clone();
  System.out.println(prototypeClass.equals(prototypeClass1));
  } catch (CloneNotSupportedException e) {
            e.printStackTrace();
  }

    }
}

输出

false

可以看到同过克隆方法产生了一个新的对象

注意事项

此外还要注意深拷贝和前拷贝的区别

  • 浅拷贝是指针拷贝,(java中没有指针,或者说是引用拷贝),操作的是栈中的数据,相当于复制了一份数值,或者是一个指针变量(指向的数据不变),java中只是产生一个新的引用量(其指向的对象不变)
  • 深拷贝是对象拷贝,操作的是堆中的数据,相当于在堆中产生一个新的对象

浅拷贝的对象如果包含引用或者是指针,当修个这个对象时,会引起原来对象的变化,这就非常危险,为了避免需要将包含的对象在堆中new 出来(即做深拷贝处理,相对比较简单)
参考 :百度百科

Sort:  

Congratulations @hiquanta! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Coin Marketplace

STEEM 0.20
TRX 0.12
JST 0.028
BTC 64252.58
ETH 3495.24
USDT 1.00
SBD 2.50