23种设计模式——原型模式
1 浅克隆package com mjh prototype;import java util Date; *** 实现一个接口
23种设计模式——原型模式
1.浅克隆
package com.mjh.prototype;
import java.util.Date;
/**
* 实现一个接口 Cloneable
* 重写一个方法 clone()
*/
public class Video implements Cloneable{
private String name;
private Date createTime;
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public Video() {
}
public Video(String name, Date createTime) {
this.name = name;
this.createTime = createTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Video{" +
"name='" + name + '\'' +
", createTime=" + createTime +
'}';
}
}
package com.mjh.prototype;
import java.util.Date;
public class BiLi {
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=>hash:"+v1.hashCode());
//v1克隆v2
Video v2= (Video) v1.clone();
System.out.println("v2=>"+v2);
System.out.println("v2=>hash:"+v2.hashCode());
v2.setName("123");
System.out.println(v2);
}
}
2.深克隆
package com.mjh.prototype.demo02;
import java.util.Date;
/**
* 实现一个接口 Cloneable
* 重写一个方法 clone()
*/
public class Video implements Cloneable{
private String name;
private Date createTime;
protected Object clone() throws CloneNotSupportedException {
Object obj= super.clone();
//实现深克隆 序列化、反序列化
Video v= (Video) obj;
//将这个对象的属性也进行克隆
v.createTime = (Date) this.createTime.clone();
return obj;
}
public Video() {
}
public Video(String name, Date createTime) {
this.name = name;
this.createTime = createTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return "Video{" +
"name='" + name + '\'' +
", createTime=" + createTime +
'}';
}
}
package com.mjh.prototype.demo02;
import java.util.Date;
public class BiLi {
public static void main(String[] args) throws CloneNotSupportedException {
//原型对象
Date date=new Date();
Video v1= new Video("你好", date);
//v1克隆v2
Video v2= (Video) v1.clone();
System.out.println("v1=>"+v1);
System.out.println("v1=>hash:"+v1.hashCode());
System.out.println("v2=>"+v2);
System.out.println("===========================================");
date.setTime(2020213);
System.out.println("v1=>"+v1);
System.out.println("v2=>"+v2);
System.out.println("v2=>hash:"+v2.hashCode());
}
}