package com.maom.design.D_11_Flyweight;
import java.util.HashMap;
import java.util.Map;
/**
* @Title: D_11_Flyweight
* @Description: 11_享元模式
* @Author maohb
* @Version 1.0
*/
public class D_11_Flyweight {
public static void main(String[] args) {
TeacherFactory factory = new TeacherFactory();
Teacher teacher1 = factory.getTeacher("0102034");
Teacher teacher2 = factory.getTeacher("0102035");
Teacher teacher3 = factory.getTeacher("0102034");
Teacher teacher4 = factory.getTeacher("0102037");
System.out.println(teacher1.getNumber());
System.out.println(teacher2.getNumber());
System.out.println(teacher3.getNumber());
System.out.println(teacher4.getNumber());
if(teacher1 == teacher3) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
class Teacher extends Person {
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Teacher(String name, int age, String number) {
super(name, age);
this.number = number;
}
public Teacher() {
super();
}
}
/** 享元工厂 */
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;
}
}
设计模式笔记_11_享元模式
最新推荐文章于 2024-09-10 17:07:09 发布