package prototype.shallow;import java.util.Date;publicclassVideoimplementsCloneable{private String name;private Date publishTime;publicVideo(String name, Date publishTime){this.name = name;this.publishTime = publishTime;}publicVideo(){}public String getName(){return name;}publicvoidsetName(String name){this.name = name;}public Date getPublishTime(){return publishTime;}publicvoidsetPublishTime(Date publishTime){this.publishTime = publishTime;}@Overrideprotected Object clone()throws CloneNotSupportedException {returnsuper.clone();}@Overridepublic String toString(){return"Video [name="+ name +", publishTime="+ publishTime +"]";}}
package prototype.shallow;import java.util.Date;publicclassMain{publicstaticvoidmain(String[] args)throws CloneNotSupportedException {
Date date =newDate();
Video video =newVideo("VideoName", date);
Video cloneVideo =(Video)video.clone();
System.out.println(video);
System.out.println(cloneVideo);
date.setTime(1231241);
System.out.println(video);
System.out.println(cloneVideo);}}
深拷贝
package prototype.deep;import java.util.Date;publicclassVideoimplementsCloneable{private String name;private Date publishTime;publicVideo(String name, Date publishTime){this.name = name;this.publishTime = publishTime;}publicVideo(){}public String getName(){return name;}publicvoidsetName(String name){this.name = name;}public Date getPublishTime(){return publishTime;}publicvoidsetPublishTime(Date publishTime){this.publishTime = publishTime;}@Overrideprotected Object clone()throws CloneNotSupportedException {
Object obj =super.clone();
Video v =(Video)obj;
v.publishTime =(Date)this.publishTime.clone();return obj;}@Overridepublic String toString(){return"Video [name="+ name +", publishTime="+ publishTime +"]";}}
package prototype.deep;import java.util.Date;publicclassMain{publicstaticvoidmain(String[] args)throws CloneNotSupportedException {
Date date =newDate();
Video video =newVideo("VideoName", date);
Video cloneVideo =(Video)video.clone();
System.out.println(video);
System.out.println(cloneVideo);
date.setTime(1231241);
System.out.println(video);
System.out.println(cloneVideo);}}
GoF23 原型模式学习笔记 1. 实现Cloneable接口 2. 重写clone方法应用场景: 1. Spring Bean 的创建:单例模式、原型模式 2. 与工厂模式一起使用,代替 new 浅拷贝代码中表现为cloneVideo的publishTime只是指向了原video的publishTimepackage prototype.shallow;import java.util.Date;public class Video implements Cloneable