设计模式-享元模式(Flyweight)

享元模式是构造型模式之一,它通过与其他类似对象共享数据来减少内存占用

 

角色和职责:

1.抽象享元角色()-Person:

  享元角色的公共接口

2.具体享元角色()-Teacher:

    抽象享元角色的具体实现类

3.享元工厂角色()-TeacherFactory:

    负责创建和管理享元角色

 

UML图:

 

具体代码如下:

/**
 * 一个人
 */
public class Person {
    private String name;//姓名
    private int age;//年龄

    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 class Teacher extends Person{
    private String number;//工号

    public Teacher(String number){
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
/**
 *   负责创建和管理享元角色
 */
public class TeacherFactory {
    private Map<String,Teacher> map= null;//享元数据的存放点

    public TeacherFactory(){
        this.map = new HashMap<String,Teacher>();
    }

    /**
     * 返回老师
     * @return
     */
    public Teacher getTeacher(String number){
        Teacher teacher = map.get(number);
        if(teacher == null){
            teacher = new Teacher(number);
            map.put(number,teacher);
        }
        return teacher;
    }
}
public class Main {
    public static void main(String[] args) {
        TeacherFactory factory = new TeacherFactory();//创建老师生产类
        Teacher teacher001 = factory.getTeacher("0001");//
        Teacher teacher002 = factory.getTeacher("0002");
        Teacher teacher = factory.getTeacher("0001");
        Teacher teacher004 = factory.getTeacher("0004");

        System.out.println(teacher001.getNumber());
        System.out.println(teacher002.getNumber());
        System.out.println(teacher.getNumber());
        System.out.println(teacher004.getNumber());

        if(teacher001 == teacher){//查看两次对象是否相同
            System.out.println(true);
        }else{
            System.out.println(teacher001);
            System.out.println(teacher);
            System.out.println(false);
        }
    }
}

 

应用场景:

  • 在 JDK 的设计里,也有很享元模式,如一些常量池的设计(String 常量池、Integer 常量池等等)
  • 如果一个系统中存在大量的相同或者相似的对象,由于这类对象的大量使用,会造成系统内存的耗费,可以使用享元模式来减少系统中对象的数量。

 

源码地址:https://github.com/qjm201000/design_pattern_flyweight.git

posted @ 2018-12-04 17:15  qjm201000  阅读(144)  评论(0编辑  收藏  举报