Java 实现享元(Flyweight)模式的示例代码分享

java教程评论359 views阅读模式

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

以上就是Java 实现享元(Flyweight)模式的示例代码分享的详细内容,更多请关注php教程其它相关文章!

企鹅博客
  • 本文由 发表于 2019年9月21日 00:55:25
  • 转载请务必保留本文链接:https://www.qieseo.com/329481.html

发表评论