本文共 3044 字,大约阅读时间需要 10 分钟。
原型模式主要用于复制对象,尤其是创建过程很复杂的情况,原型模式可以简化创建过程,提高性能,一般用于一个对象的属性已经确定,需要产生很多相同对象的时候,其实很少使用这种模式。
实现原型模式需要两点:第一是要实现Cloneable 接口,第二是重写Object类的clone方法。
这里只说明如何实现原型模式,模拟场景无法体现提高性能。
1、实现Cloneable 接口
public class Prototype implements Cloneable { private long count; public Prototype(long count) { this.count = count; } @Override public Object clone() { Object prototype = null; try { prototype = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return prototype; } public void say() { System.out.println(count); }}
2、测试
public class Test { public static void main(String[] args) { Prototype house = new Prototype(5); long start = System.currentTimeMillis(); for (int i=0;i<10000;i++) { Prototype p = (Prototype) house.clone(); p.say(); } long end = System.currentTimeMillis(); System.out.println(end-start); }}
上面的实现只是浅克隆,如果类里面有一个成员类的引用,需要实现深克隆,只需要让成员类实现Cloneable接口,重写clone方法。
改写上面的代码,实现深克隆。
定义一个成员类,
public class Address implements Cloneable{ public String getCity() { return city; } public void setCity(String city) { this.city = city; } private String city; public Address(String city) { this.city = city; } @Override public String toString() { return this.city; } @Override public Object clone() { Object prototype = null; try { prototype = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return prototype; }}
改写之前的 Prototype 类,增加对Address的引用,
public class Prototype implements Cloneable { private long count; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } private Address address; public Prototype(long count, Address address) { this.count = count; this.address = address; } @Override public Object clone() { Object prototype = null; try { prototype = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return prototype; } public void say() { System.out.println(count); System.out.println(address.toString()); }}
测试:
public class Test { public static void main(String[] args) { Address address = new Address("北京"); Prototype house = new Prototype(5, address); long start = System.currentTimeMillis(); ListobjList = new ArrayList<>(); for (int i=0;i<10;i++) { Prototype p = (Prototype) house.clone(); objList.add(p); p.say(); } long end = System.currentTimeMillis(); System.out.println(end-start); house.setAddress(new Address("上海")); for (Prototype p : objList) { p.say(); } }}
需要注意的是:
如果调用某个对象的clone方法,而该对象类没有实现Cloneable接口,会在运行时报错。
转载地址:http://tnnxi.baihongyu.com/