原型模式
介绍
原型模式用于创建重复的对象,同时又能保证性能。
java实现
实现原型模式需要两步:
- 实现
Cloneable
接口 - 重写
clone
方法
例如我们定义一个Video
类
import lombok.*;
import java.time.*;
@Data
@AllArgsConstructor
public class Video implements Cloneable{
private String name;
private LocalDateTime createTime;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
创建main函数,测试clone
方法:
import java.time.*;
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
Video v1 = new Video("设计模式.mp4", localDateTime);
Video v2 = (Video) v1.clone();
System.out.println(v1);
System.out.println(v2);
System.out.println(v1 == v2);
}
}
运行结果:
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
false
可以看出v1和v2是两个不同的对象,但是内容完全相同
深克隆
刚才的代码虽然实现了克隆,但是v1和v2中的createTime
属性都是LocalDateTime
类的对象的引用:
import java.time.*;
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
Video v1 = new Video("设计模式.mp4", localDateTime);
Video v2 = (Video) v1.clone();
System.out.println(v1.getCreateTime() == v2.getCreateTime());
}
}
运行结果:
true
要解决这个问题只需要改造一下clone
方法,在clone
对象的时候,将createTime
属性同时克隆一份
import cn.hutool.core.util.*;
import lombok.*;
import java.time.*;
@Data
@AllArgsConstructor
public class Video implements Cloneable {
private String name;
private LocalDateTime createTime;
@Override
protected Object clone() throws CloneNotSupportedException {
Video v = (Video) super.clone();
v.setCreateTime(ObjectUtil.clone(createTime));
return v;
}
}
再次运行测试:
import java.time.*;
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
LocalDateTime localDateTime = LocalDateTime.of(2020, 2, 8, 19, 32);
Video v1 = new Video("设计模式.mp4", localDateTime);
Video v2 = (Video) v1.clone();
System.out.println(v1);
System.out.println(v2);
System.out.println(v1.getCreateTime() == v2.getCreateTime());
}
}
运行结果:
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
Video(name=设计模式.mp4, createTime=2020-02-08T19:32)
false