享元模式
文章目录
定义:使用共享对象可有效地支持大量的细粒度的对象。
其实就是通过共享相同的对象来减少内存的使用。
代码实现:
@AllArgsConstructor
public class Student {
private int id;
private String name;
}
public class StudentFactory {
// 使用map缓存共享对象
private static final Map<Integer,Student> cache = new HashMap<>();
public static Student create(int id,String name){
// 不直接创建,而是从缓存池中获取
Student student = cache.get(id);
if (student == null) {
student=new Student(id,name);
cache.put(id,student);
}
return student;
}
}
客户端的使用:
StudentFactory.create(1,"tony");
享元模式的好处是能节省内存。
另外享元模式在多线程下需要注意线程安全问题。
享元模式看上去类似于单例模式,两者的区别是:享元模式是要求对象不变,单例模式是不允许创建新实例。
文章作者 梧桐碎梦
上次更新 2023-04-29 10:52:34