最聪明的人是最不愿浪费时间的人。 ——但丁
1、定义
享元模式 (Flyweight Pattern),享元模式是以共享的模式来支持大量细粒度对象的复用。
2、组成角色
image.png享元模式包含的角色列举如下:
- 抽象享元角色(Flyweight):一般是一个具体的抽象类,同时定义了对象的外部状态和内部状态的接口或实现;
- 具体享元角色(ConcreteFlyweight):具体的一个产品类,实现了抽象享元角色中定义的接口,该角色需要注意的是内部状态的处理应该与环境无关;
- 享元工厂(FlyweightFactory):该角色指责一般比较清晰,就是一个池工厂,提供池对象和获取池中对象的方法
3、使用实例
抽象享元角色类
public abstract class ExamInfo {
private String student;
private String subject;
public ExamInfo(String subject) {
this.subject = subject;
}
public String getStudent() {
return student;
}
public void setStudent(String student) {
this.student = student;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public abstract void operate();
}
具体享元角色类
public class ConcreteExamInfo extends ExamInfo{
public ConcreteExamInfo(String subject) {
super(subject);
}
@Override
public void operate() {
System.out.println(this.getStudent()+"正在考"+this.getSubject());
}
}
享元工厂类
public class ExamInfoFactory {
private static Map<String,ExamInfo> examInfoMap = new HashMap<>();
public static ExamInfo getExamInfo(String subject){
ExamInfo examInfo;
if(examInfoMap.containsKey(subject)){
System.out.println("直接从池中获取..." + subject);
examInfo = examInfoMap.get(subject);
}else {
examInfo = new ConcreteExamInfo(subject);
examInfoMap.put(subject,examInfo);
System.out.println("建立对象,并放到池中..." + subject);
}
return examInfo;
}
}
客户端类
public class Main {
public static void main(String[] args) {
ExamInfo examInfo = ExamInfoFactory.getExamInfo("数学");
examInfo.setStudent("小红");
examInfo.operate();
examInfo = ExamInfoFactory.getExamInfo("数学");
examInfo.setStudent("小明");
examInfo.operate();
examInfo = ExamInfoFactory.getExamInfo("数学");
examInfo.setStudent("小李");
examInfo.operate();
examInfo = ExamInfoFactory.getExamInfo("语文");
examInfo.setStudent("小红");
examInfo.operate();
examInfo = ExamInfoFactory.getExamInfo("语文");
examInfo.setStudent("小明");
examInfo.operate();
examInfo = ExamInfoFactory.getExamInfo("语文");
examInfo.setStudent("小李");
examInfo.operate();
}
}
测试结果打印
image.png
网友评论