0
点赞
收藏
分享

微信扫一扫

设计模式系列----原型模式理解

1、使用场景

老规矩,先来使用场景:

原型模式主要是针对创建和实例化对象耗时较长,耗资源较多的情况,因为使用原型模式创建对象是直接在内存中拷贝,不需要使用构造器进行构造,没有初始化的过程。

2、没使用原型模式

User user = new User();

3、一句话概括原型模式

原型模式就是通过重写clone方法,实现深拷贝,通过复制实现对象的创建。

4、使用原型模式

public class User implements Cloneable{
private String name;
private int age;
//getter、setter、构造器
..................

//重写克隆方法:调用的是父类默认的clone方法来拷贝user类
@Override
protected Object clone(){
Object user= null;
try {
user= super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return user;
}
}

从上面可以看到,User实现了Cloneable接口,重写了clone方法,就只有一行有效代码,super.clone
其调用的就是他父类的clone方法。

进行克隆:

public class client {
public static void main(String[] args) {
User user= new User ("Tom", 2);
User user2= (User )user.clone();

System.out.println(user.hashCode()); //366712642
System.out.println(user2.hashCode()); //1829164700

可以看到输出的user和user2的hash值不同,所以两者的引用不同,不是同一个对象,属于深拷贝。

–我是“道祖且长”,一个在互联网"苟且偷生"的Java程序员
“有任何问题,可评论,我看到就会回复”


举报

相关推荐

0 条评论