ces原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。参考菜鸟教程。
原型模式主要核心为 浅拷贝 深拷贝
测试代码如下:
浅拷贝:
/**
* <p>
*
* </p>
*
* @since 2022/3/21 14:21
*/
@Data
@Slf4j
public class WeeklyLog implements Cloneable {
private Attachment attachment;
private LocalDateTime date;
private String name;
private String content;
@Override
public WeeklyLog clone() {
Object object;
try {
object = super.clone();
return (WeeklyLog) object;
} catch (Exception e) {
}
return null;
}
}
/**
* <p>
*
* </p>
*
* @since 2022/3/21 14:20
*/
@Data
public class Attachment {
private String name;
public void download() {
System.out.println("下载附件");
}
}
测试代码
WeeklyLog l1, l2;
l1 = new WeeklyLog();
Attachment attachment = new Attachment();
l1.setAttachment(attachment);
l2 = l1.clone();
System.out.println(l1 == l2);
System.out.println(l1.getAttachment() == l2.getAttachment());
深拷贝:
/**
* <p>
*
* </p>
*
* @since 2022/3/21 14:21
*/
@Data
@Slf4j
public class WeeklyLog2 implements Serializable {
private Attachment2 attachment;
private LocalDateTime date;
private String name;
private String content;
public WeeklyLog2 deepClone() throws Exception {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bao);
oos.writeObject(this);
ByteArrayInputStream bas = new ByteArrayInputStream(bao.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bas);
return (WeeklyLog2) ois.readObject();
}
}
/**
* <p>
*
* </p>
*
* @since 2022/3/21 14:20
*/
@Data
public class Attachment2 implements Serializable {
private String name;
public void download() {
System.out.println("下载附件");
}
}
测试代码
WeeklyLog2 l1, l2;
l1 = new WeeklyLog2();
Attachment2 attachment = new Attachment2();
l1.setAttachment(attachment);
l2 = l1.deepClone();
System.out.println(l1 == l2);
System.out.println(l1.getAttachment() == l2.getAttachment());
1、通过原型模式可以简化创建重量级对象的过程,并提高程序的效率。
2、原型设计模式是动态获取对象运行时的状态进行创建对象的。
3、使用原型设计模式可以使代码变的更加灵活,因为当原型类发生变化(增、减属性)时,克隆的对象也会做出相应的改变。
4、对已经创建好的类进行改造,使其支持克隆时需要修改源代码,这就是违背了开闭原则