(十)享元模式

享元模式

一、什么是享元模式

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;
	}
	
	
}

public 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 sex,String number) {
		super(name, age, sex);
		this.number = number;
	}
	
	public Teacher() {
		super();
	}
	
}

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

public class TeacherFactory {
	private Map pool;
	
	public TeacherFactory() {
		pool = new HashMap();
	}
	
	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;
	}
}

public class MainClass {
	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");
		}
	}
}


你可能感兴趣的:(设计模式,享元模式)