1.定义
Flyweight模式也叫享元模式,是结构型模式之一。它通过与其它类似对象共享数据来减少内存使用。
2.享元模式结构
3.享元模式的角色和职责
- 抽象享元角色:所有具体享元类的父类,规定一些需要实现的公共接口
- 具体享元角色:抽象享元角色的具体类,并实现了抽象享元角色规定的方法
- 享元工厂角色:负责创建和管理享元角色
4.代码演示
package test.com.flyweight; /* * 抽象享元角色 */ public class Person { private String name; private int age; private String sex; public Person(String name, int age, String sex) { super(); this.name = name; this.age = age; this.sex = sex; } public Person() { } 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 test.com.flyweight; /* * 具体享元角色 */ public class Teacher extends Person { private String num; public Teacher(String name, int age, String sex, String num) { super(name, age, sex); this.num = num; } public Teacher() { super(); } public String getNum() { return num; } public void setNum(String num) { this.num = num; } }
package test.com.flyweight; import java.util.HashMap; import java.util.Map; /* * 享元工厂角色 */ public class FlyWeightFactory { private Map<String, Teacher> pool; public FlyWeightFactory() { pool = new HashMap<String, Teacher>(); } public Teacher getTeacher(String num) { Teacher teacher = pool.get(num); if(teacher == null) { teacher = new Teacher(); teacher.setNum(num); pool.put(num, teacher); } return teacher; } }
package test.com.flyweight; /* * 测试代码 */ public class Main { public static void main(String[] args) { FlyWeightFactory fwf = new FlyWeightFactory(); Teacher teacher1 = fwf.getTeacher("01"); Teacher teacher2 = fwf.getTeacher("02"); Teacher teacher3 = fwf.getTeacher("03"); Teacher teacher4 = fwf.getTeacher("02"); System.out.println(teacher1.getNum()); System.out.println(teacher2.getNum()); System.out.println(teacher3.getNum()); System.out.println(teacher4.getNum()); if(teacher2 == teacher4) { System.out.println("true"); } else { System.out.println("false"); } } }