享元模式(FlyweightPattern)

基本介绍:

    采用一个共享来避免大量拥有相同内容对象的开销。这种开销中最常见、直观的就是内存的损耗。享元模式以共享的方式高效的支持大量的细粒度对象。


示例代码:

package org.brando;

import org.brando.FlyweightFactory.WordTypeEnum;

/**
 * 
 * 类说明: 测试类
 * @author Brando 2018年3月29日 下午2:03:59
 */
public class Launcher {

	public static void main(String[] args) {
		
		BaseWord a = FlyweightFactory.createWord(WordTypeEnum.A);
		BaseWord b = FlyweightFactory.createWord(WordTypeEnum.B);
		a.showText();
		b.showText();
		
	}
	
}

package org.brando;

/**
 * 
 * 类说明: 基础字符类
 * @author Brando 2018年5月4日 下午3:21:24
 */
public class BaseWord {

	public String text;
	
	public void showText() {
		System.out.println(this.text);
	}
	
}

package org.brando;

/**
 * 
 * 类说明: 字母A
 * @author Brando 2018年5月4日 下午4:21:46
 */
public class A extends BaseWord {

	public A() {
		this.text = "A";
	}
	
}

package org.brando;

/**
 * 
 * 类说明: 字母B
 * @author Brando 2018年5月4日 下午4:21:54
 */
public class B extends BaseWord {

	public B() {
		this.text = "B";
	}
	
}

package org.brando;

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

/**
 * 
 * 类说明: 享元工厂.
 * @author Brando 2018年5月4日 下午3:18:26
 */
public class FlyweightFactory {

	/**缓存**/
	private static Map<String, BaseWord> baseWordMap = new HashMap<String, BaseWord>();
	
	/**
	 * 
	 * 方法说明: 创建字母.
	 * @author Brando 2018年5月4日 下午3:28:58
	 * @return
	 */
	public static BaseWord createWord(WordTypeEnum wordType) {
		
		BaseWord word = baseWordMap.get(wordType.getName());
		if(word == null) {
			switch (wordType) {
			case A:
				word = new A();
				baseWordMap.put(wordType.getName(), word);
				break;
			case B:
				word = new B();
				baseWordMap.put(wordType.getName(), word);
				break;
			default:
				break;
			}
		}
		return word;
	}
	
	/**
	 * 
	 * 枚举说明: 字符类型枚举.
	 * @author Brando 2018年5月4日 下午4:17:12
	 */
	public enum WordTypeEnum {
		A("A"), B("B");
		
		private String name;
		
		WordTypeEnum(String name) {
			this.name = name;
		}
		
		public String getName() {
			return this.name;
		}
	}
	
}






猜你喜欢

转载自blog.csdn.net/lyq19870515/article/details/80196845