原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式之一。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
直接看代码 —— 代码包含了两个基础逻辑
— 浅复制
— 深复制
/**
* 原型模式 - 深克隆 deep copy
* @version 0.1
* @author BaiJing.biz
*/
public class StuDeepRun {
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
DiplomaDeep diploma = new DiplomaDeep();
Student student = new Student();
student.setName("Tom 汤姆");
diploma.setStudent(student);
diploma.show();
// 深克隆
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/tree/javasrc/testfile/a.txt"));
oos.writeObject(diploma);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/tree/javasrc/testfile/a.txt"));
DiplomaDeep clone = (DiplomaDeep)ois.readObject();
ois.close();
clone.getStudent().setName("John");
clone.show();
}
}
/**
* 原型模式 - 深克隆 : 毕业证案例
* @version 0.1
* @author BaiJing.biz
*/
public class Student implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
/**
* 原型模式 - 毕业证案例
* @version 0.1
* @author BaiJing.biz
*/
public class StuRun {
public static void main(String[] args) throws CloneNotSupportedException {
/*
必须实现 Clone and Cloneable接口
*/
Diploma diploma = new Diploma();
// Clone 毕业证对象
Diploma clone = diploma.clone();
diploma.setName("John");
clone.setName("Tom 汤姆");
diploma.show();
clone.show();
System.out.println(diploma);
System.out.println(clone);
System.out.println(diploma == clone);
}
}
/**
* 原型模式 - 浅克隆 shallow copy : 毕业证案例
* @version 0.1
* @author BaiJing.biz
*/
public class Diploma implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Diploma clone() throws CloneNotSupportedException {
return (Diploma) super.clone();
}
public void show() {
System.out.println(name + " 于2025年毕业于 BaiJing Tech University !");
}
}
/**
* 原型模式 - 深克隆 deep copy
* @version 0.1
* @author BaiJing.biz
*/
public class DiplomaDeep implements Cloneable , Serializable {
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
@Override
public Diploma clone() throws CloneNotSupportedException {
return (Diploma) super.clone();
}
public void show() {
System.out.println(student.getName() + " 于2025年毕业于 BaiJing Tech University !");
}
}
本结构通过「文件」操作了实现了「深复制」。

之原型模式(Prototype Pattern)&spm=1001.2101.3001.5002&articleId=150421883&d=1&t=3&u=b97875186108411982d10d88377d03ec)
326

被折叠的 条评论
为什么被折叠?



