단일 공장 싱글 톤 팩 토리

2173 단어 디자인 모드
public class SingletonFactory {
	@SuppressWarnings("rawtypes")
	private static Map instaces = new ConcurrentHashMap();
	@SuppressWarnings("rawtypes")
	private static Map> weakReferenceInstaces = new ConcurrentHashMap>();
	
	/**
	 *             ,       ,      gc 
	 * @param className
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("unchecked")
	public static  E getInstace(Class className){
		Object instace =instaces.get(className);
		if(instace==null){
			synchronized (SingletonFactory.class) {
				instace =instaces.get(className);
				if(instace==null){
					try {
						instace = className.newInstance();
					} catch (InstantiationException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					instaces.put(className,instace);
				}
			}
		}
		return (E)instace;
	}
	
	/**
	 *           ,       ,      gc 
	 * 
	 * @param className
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("unchecked")
	public static  E getWeakInstace(Class className) {
		WeakReference reference = weakReferenceInstaces.get(className);
		Object instace =reference==null?null:reference.get();
		if(instace==null){
			synchronized (SingletonFactory.class) {
				reference = weakReferenceInstaces.get(className);
				instace =reference==null?null:reference.get();
				if(instace==null){
					try {
						instace = className.newInstance();
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					weakReferenceInstaces.put(className,new WeakReference(instace));
				}
			}
		}
		return (E)instace;
	}
	

}

단일 모델 과 공장 모델 을 결합 하 다. 
본 공장 에서 만 든 실 체 는 단일 사례 임 을 보증 합 니 다. 
이러한 단 례 는 구축 방법 을 설정 하여 공공의 편 의 를 위해 계승 할 수 있다

좋은 웹페이지 즐겨찾기