Java 实现享元(Flyweight)模式

/**
 * 字母
 * @author stone
 *
 */
public class Letter {

	private String name;

	public Letter(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
}
/**
 * 一个产生字母对象的 享元工厂(单例工厂)
 * @author stone
 *
 */
public class LetterFactory {
	private Map<String, Letter> map;
	private static LetterFactory instance = new LetterFactory();
	
	private LetterFactory() {
		map = new HashMap<String, Letter>();
	}
	
	public static LetterFactory getInstance() {
		return instance;
	}
	
	public void add(Letter letter) {
		if (letter != null && !map.containsKey(letter.getName())) {
			map.put(letter.getName(), letter);
		}
		System.out.println("map.size====" + map.size());
	}
	
	public Letter get(String name) {
		return map.get(name);
	}
	
}

/*
 * 享元(Flyweight)模式	结构型模式		主要目的是实现对象的共享
 * 		字面上看就是 一个 共享元件的模式,这里是将 一些在系统中须要反复使用的对象。共享成单个元件
 * 
 *  像JDBC数据库连接池、线程池等 都是应用了享元模式
 *  	数据库连接池: 创建了一定数量的连接。存入池中。用到时取出。释放时再存入
 *  	池程池:相似,也是 用到时取出,释放时再存入
 *  所以一般 都会有一个集合来存储元件。有一个享元工厂进行元件的管理。

*/ public class Test { public static void main(String[] args) { LetterFactory factory = LetterFactory.getInstance(); String word = "easiness"; addLetterByName(factory, word); getLetter(factory, word); } //加入字母对象 static void addLetterByName(LetterFactory factory, String word) { for (char c : word.toCharArray()) { factory.add(new Letter(c + "")); } } //输出字母对象 static void getLetter(LetterFactory factory, String word) { for (char c : word.toCharArray()) { System.out.println(factory.get(c + "")); } } }


打印

map.size====1
map.size====2
map.size====2
map.size====3
map.size====4
map.size====5
map.size====5
flyweight.Letter@3343c8b3
flyweight.Letter@272d7a10
flyweight.Letter@3343c8b3
flyweight.Letter@1aa8c488
flyweight.Letter@3dfeca64
flyweight.Letter@22998b08
flyweight.Letter@1aa8c488


原文地址:https://www.cnblogs.com/lcchuguo/p/5171357.html