原型模式
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。
1. 创建原型接口
// 原型接口
public abstract class Student implements Cloneable {
private String id;
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// 复制现有实例来生成新实例
@Override
protected Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
2. 创建实例对象
public class StudentA extends Student {
public StudentA(){
setType("StudentA");
}
}
public class StudentB extends Student {
public StudentB(){
setType("StudentB");
}
}
3. 创建缓存类
public class Prototype {
private Hashtable<String,Student> hashtable = new Hashtable<>();
// 从缓存中获取相应的对象
public Student getStudent(String id){
Student student = hashtable.get(id);
return (Student) student.clone();
}
// 将数据加入缓存
protected void info(){
StudentA studentA = new StudentA();
studentA.setId("1");
hashtable.put(studentA.getId(),studentA);
StudentB studentB = new StudentB();
studentB.setId("2");
hashtable.put(studentB.getId(),studentB);
}
}
4. 创建客户端
public static void main(String[] args) {
Prototype prototype = new Prototype();
prototype.info();
Student student = prototype.getStudent("1");
System.out.println(student.getType());
Student student2 = prototype.getStudent("2");
System.out.println(student2.getType());
}
}
打印结果如下:
{\__/} {\__/}
( ·-·) (·-· )
/ >------------------------------------------------< \
| ☆ |
| ☆ |
| ★ |
| ☆ |
| ☆ |
| |
-------------------------------------
如有兴趣可以关注我的公众号