享元模式
标签:设计模式

享元模式(Flyweight)

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

1. 享元模式的角色及其职责

1.1 抽象享元角色

所有具体享元类的父类,规定一些需要实现的公共接口

Person

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/01
 */
public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = 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;
    }
}

1.2 具体享元角色

抽象享元角色的具体实现类,并实现了抽象享元角色规定的方法

Teacher

package com.liuyao;

/**
 * @author liuyao
 * @date 2018/08/01
 */
public class Teacher extends Person {
    private String no;

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public Teacher(String name, int age, String no) {
        super(name, age);
        this.no = no;
    }

    public Teacher() {
    }
}

1.3 享元工厂角色

负责创建和管理享元角色

TeacherFactory

package com.liuyao;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuyao
 * @date 2018/08/01
 */
public class TeacherFactory {
    private Map<String,Teacher> pool;

    public TeacherFactory() {
        pool=new HashMap<String,Teacher>();
    }

    public Teacher getTeacher(String no){
        Teacher teacher=pool.get(no);
        if (teacher == null){
            teacher = new Teacher();
            teacher.setNo(no);
            pool.put(no,teacher);
        }
        return teacher;
    }
}

Main

package com.liuyao;

public class Main {

    public static void main(String[] args) {
        TeacherFactory factory = new TeacherFactory();
        Teacher teacher = factory.getTeacher("1234");
        Teacher teacher1 = factory.getTeacher("1235");
        Teacher teacher2 = factory.getTeacher("1234");

        System.out.println(teacher.getNo());
        System.out.println(teacher1.getNo());
        System.out.println(teacher2.getNo());

        System.out.println(teacher == teacher1);
        System.out.println(teacher == teacher2);
    }
}

//1234
//1235
//1234
//false
//true

可见当no相同的时候,用的是同一个对象

  • 2 min read

CONTRIBUTORS


  • 2 min read