[设计模式]原型模式
[设计模式]原型模式
- 原型模式的主要思想就是克隆。
- 需要克隆的类实现Cloneable接口。
- 对象使用clone()方法。
一、浅克隆
-
video类
public class Video implements Cloneable{ private String title; private Date createTime; public Video(String title, Date createTime) { this.title = title; this.createTime = createTime; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return "Video{" + "title='" + title + '\'' + ", createTime=" + createTime + '}'; } } -
测试类
public class Copy { public static void main(String[] args) throws CloneNotSupportedException { Date date = new Date(); Video v1 = new Video("小猪佩奇",date); System.out.println("v1=>"+v1); System.out.println("v1=>"+v1.hashCode()); Video v2 = (Video)v1.clone(); System.out.println("v1=>"+v2); System.out.println("v2=>"+v2.hashCode()); } } -
运行结果
v1=>Video{title='小猪佩奇', createTime=Sat Jun 13 12:29:03 CST 2020} v1=>2133927002 v2=>Video{title='小猪佩奇', createTime=Sat Jun 13 12:29:03 CST 2020} v2=>1836019240
二、深克隆
-
video类
public class Video implements Cloneable{ private String title; private Date createTime; public Video(String title, Date createTime) { this.title = title; this.createTime = createTime; } @Override protected Object clone() throws CloneNotSupportedException { Video video = (Video)super.clone(); video.createTime = (Date)createTime.clone(); return video; } @Override public String toString() { return "Video{" + "title='" + title + '\'' + ", createTime=" + createTime + '}'; } } -
测试类
public class Copy { public static void main(String[] args) throws CloneNotSupportedException { Date date = new Date(); Video v1 = new Video("小猪佩奇",date); System.out.println("v1=>"+v1); System.out.println("v1=>"+v1.hashCode()); Video v2 = (Video)v1.clone(); System.out.println("v2=>"+v2); System.out.println("v2=>"+v2.hashCode()); System.out.println("=================================="); date.setTime(22222222); System.out.println("v1=>"+v1); System.out.println("v1=>"+v1.hashCode()); System.out.println("v2=>"+v2); System.out.println("v2=>"+v2.hashCode()); } } -
运行结果
v1=>Video{title='小猪佩奇', createTime=Sat Jun 13 12:38:10 CST 2020} v1=>2133927002 v2=>Video{title='小猪佩奇', createTime=Sat Jun 13 12:38:10 CST 2020} v2=>1836019240 ================================== v1=>Video{title='小猪佩奇', createTime=Thu Jan 01 14:10:22 CST 1970} v1=>2133927002 v2=>Video{title='小猪佩奇', createTime=Sat Jun 13 12:38:10 CST 2020} v2=>1836019240

浙公网安备 33010602011771号