首页 > 技术文章 > Java设计模式--享元模式

mxh-java 2019-06-22 19:12 原文

import java.util.HashMap;

/**
 * 享元模式
 * @author 尘世间迷茫的小书童
 *
 */
public class Flyweight {
	
	public static void main(String[] args) {
		for(int i=0; i<5; i++) {
			Cluster library = ClusterFactory.getCluster("阅读");
			library.setClusterName("中国国家图书馆");
			library.setClusterType("一级");
			library.use();
			System.out.println(library);
			
			Cluster gymnasium = ClusterFactory.getCluster("运动");
			gymnasium.setClusterName("中国国家体育馆");
			gymnasium.setClusterType("一级");
			gymnasium.use();
			System.out.println(gymnasium);
		}
		
		int count = ClusterFactory.getClusterSize();
		System.out.println("对象池: " + count);
	}
}

class Library extends Cluster {
	
	@Override
	public void use() {
		// TODO Auto-generated method stub
		System.out.println("图书馆名称: " + this.clusterName + " 建筑类别: " + this.clusterType + " 用处: " + this.effect);
	}

	public Library(String effect) {
		super();
		this.effect = effect;
	}
	
}

class Gymnasium extends Cluster {
	
	@Override
	public void use() {
		// TODO Auto-generated method stub
		System.out.println("体育馆名称: " + this.clusterName + " 建筑类别: " + this.clusterType + " 用处: " + this.effect);
	}

	public Gymnasium(String effect) {
		super();
		this.effect = effect;
	}
	
}

class ClusterFactory {
	
	/**
	 * 对象池
	 */
	private static final HashMap<String, Cluster> map = new HashMap<String, Cluster>();
	
	private ClusterFactory() {}
	
	public static Cluster getCluster(String effect) {
		Cluster cluster = map.get(effect);
		if(null == cluster) {
			if("阅读".equals(effect)) {
				cluster = new Library("阅读");
				map.put("阅读", cluster);
			}
			if("运动".equals(effect)) {
				cluster = new Gymnasium("运动");
				map.put("运动", cluster);
			}
		}
		return cluster;
	}
	
	public static int getClusterSize() {
		return map.size();
	}
}

  推荐阅读: https://www.cnblogs.com/V1haoge/p/6542449.html                               

推荐阅读