享元模式详解

 

SignInfo.java

public class SignInfo {

	/**
	 * 报名人员ID.
	 */
	private String id;
	/**
	 * 考试地点.
	 */
	private String location;
	/**
	 * 考试科目.
	 */
	private String subject;
	/**
	 * 邮寄地址.
	 */
	private String postAddress;
	/**
	 * 获取id.
	 * @return the id
	 */
	public String getId() {
		return id;
	}
	/**
	 * 设置id.
	 * @param newId the id to set
	 */
	public void setId(String newId) {
		id = newId;
	}
	/**
	 * 获取location.
	 * @return the location
	 */
	public String getLocation() {
		return location;
	}
	/**
	 * 设置location.
	 * @param newLocation the location to set
	 */
	public void setLocation(String newLocation) {
		location = newLocation;
	}
	/**
	 * 获取subject.
	 * @return the subject
	 */
	public String getSubject() {
		return subject;
	}
	/**
	 * 设置subject.
	 * @param newSubject the subject to set
	 */
	public void setSubject(String newSubject) {
		subject = newSubject;
	}
	/**
	 * 获取postAddress.
	 * @return the postAddress
	 */
	public String getPostAddress() {
		return postAddress;
	}
	/**
	 * 设置postAddress.
	 * @param newPostAddress the postAddress to set
	 */
	public void setPostAddress(String newPostAddress) {
		postAddress = newPostAddress;
	}
	
}

SignInfoForPool.java

public class SignInfoForPool extends SignInfo {

	/**
	 * 定义一个对象池提取的key值.
	 */
	private String key;
	
	public SignInfoForPool(final String key) {
		this.key = key;
	}

	/**
	 * 获取key.
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * 设置key.
	 * @param newKey the key to set
	 */
	public void setKey(String newKey) {
		key = newKey;
	}
	
}

SignInfoFactory.java

public class SignInfoFactory {

	/**
	 * 池容器.
	 */
	private static Map<String, SignInfo> pool = new HashMap<>(64);
	
	public static SignInfo getSignInfo(final String key) {
		// 设置返回对象.
		SignInfo result = null;
		// 池中没有该对象,则建立,并放入池中.
		if (!pool.containsKey(key)) {
			System.out.println(key + "----建立对象,并放置到池中.");
			result = new SignInfoForPool(key);
			pool.put(key, result);
		} else {
			result = pool.get(key);
			System.out.println(key + "----直接从池中取得.");
		}
		return result;
	}
}

Client.java

public class Client {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 初始化对象池.
		for (int i=0; i<4; i++) {
			String subject = "科目" + i;
			// 初始化地址.
			for (int j=0; j<30; j++) {
				String key = subject + "考试地点" + j;
				SignInfoFactory.getSignInfo(key);
			}
		}
		
		// 获取对象.
		SignInfo signInfo = SignInfoFactory.getSignInfo("科目1考试地点1");
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值