Develop

[java] 초간단 싱글톤(Singleton) 패턴 샘플 코드

by hooni posted Nov 18, 2013
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

싱글톤 패턴 간단 예제

import java.util.HashMap;

class Singleton {
    private static HashMap map = new HashMap();
    //private static Logger logger = Logger.getRootLogger();

    protected Singleton() {
        // Exists only to thwart instantiation
    }

    public static synchronized Singleton getInstance(String classname) {
        Singleton singleton = (Singleton)map.get(classname);
        if(singleton != null) {
            System.out.println("got singleton from map: " + singleton);
            return singleton;
        }
        try {
            singleton = (Singleton)Class.forName(classname).newInstance();
        }
        catch(ClassNotFoundException cnf) {
            System.out.println("Couldn't find class " + classname);     
        }
        catch(InstantiationException ie) {
            System.out.println(
            "Couldn't instantiate an object of type " + classname);
        }
        catch(IllegalAccessException ia) {
            System.out.println("Couldn't access class " + classname);     
        }
        map.put(classname, singleton);
        System.out.println("created singleton: " + singleton);
        return singleton;
    }
}

class SingletonTest {
    public static void main(String[] args) {
    }
}