一、什么是享元模式
Flyweight模式也叫享元模式,是构造型模式之一,它通过与其他类似对象共享数据来减小内存占用。
二、享元模式的结构
三、享元模式的角色和职责
抽象享元角色:所有具体享元类的父类,规定一些需要实现的公共接口。
具体享元角色:抽象享元角色的具体实现类,并实现了抽象享元角色规定的方法。
享元工厂角色: 负责创建和管理享元角色。
代码实现:
抽象享元角色类:
package com.qianyan.flyweight;
public class Person {
private String name;
private int age;
private String sex;
public Person() {
}
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
具体享元模式:
package com.qianyan.flyweight;
public class Teacher extends Person{
//编号
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Teacher() {
}
public Teacher(String name, int age, String sex, String number) {
super(name, age, sex);
this.number = number;
}
}
享元工厂模式:
package com.qianyan.flyweight;
import java.util.HashMap;
import java.util.Map;
public class TeacherFactory {
private Map<String, Teacher> pool;
public TeacherFactory() {
pool = new HashMap<String, Teacher>();
}
public Teacher getTeacher(String number) {
Teacher teacher = pool.get(number);
if(teacher == null){
teacher = new Teacher();
teacher.setNumber(number);
pool.put(number, teacher);
}
return teacher;
}
}
测试类:
package com.qianyan.flyweight;
public class MainClass {
public static void main(String[] args) {
TeacherFactory teaFactory = new TeacherFactory();
Teacher tea1 = teaFactory.getTeacher("00001");
Teacher tea2 = teaFactory.getTeacher("00002");
Teacher tea3 = teaFactory.getTeacher("00003");
Teacher tea4 = teaFactory.getTeacher("00001");
Teacher tea5 = teaFactory.getTeacher("00005");
System.out.println(tea1.getNumber());
System.out.println(tea2.getNumber());
System.out.println(tea3.getNumber());
System.out.println(tea4.getNumber());
System.out.println(tea5.getNumber());
if(tea1 == tea4)
System.out.println("true");
else
System.out.println("false");
}
}
测试结果:
00001
00002
00003
00001
00005
true