Home > Java > javaTutorial > Sharing sample code for implementing Flyweight mode in Java

Sharing sample code for implementing Flyweight mode in Java

黄舟
Release: 2017-03-10 13:30:36
Original
1293 people have browsed it

Sample code sharing for Java implementation of Flyweight mode

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

	private String name;

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

	public String getName() {
		return name;
	}
}
Copy after login
/**
 * 一个产生字母对象的 享元工厂(单例工厂)
 * @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);
	}
	
}
Copy after login


/*
 * 享元(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 + ""));
		}
	}
}
Copy after login

Print

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
Copy after login

The above is the detailed content of Sharing sample code for implementing Flyweight mode in Java. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template