싱글톤 (Singleton) 은 어플리케이션의 시작부터 종료될 때 까지  한번의 생성(new)으로 고정된 메모리영역을 가지기 때문에  메모리를 효율적으로 사용 할 수 있다. 또한 싱글톤의 인스턴스는  전역적으로 사용되기 때문...

[안드로이드] 싱글톤(Singleton) 사용





싱글톤 (Singleton) 은 어플리케이션의 시작부터 종료될 때 까지 
한번의 생성(new)으로 고정된 메모리영역을 가지기 때문에 
메모리를 효율적으로 사용 할 수 있다. 또한 싱글톤의 인스턴스는 
전역적으로 사용되기 때문에 다른 클래스의 인스턴스들이 
데이터를 공유 변경이 가능하다는 장점을 가지고 있다.


싱글톤 패턴에는 여러가지가 있는데, 대표적으로 4가지정도 확인해야할 필요가 있습니다.


1. Eager Initialization (이른 초기화 방식)

 싱글톤 객체를 instance 라는 변수로 미리 생성해 놓고 사용하는 방식입니다.

public class Singleton {
    private static final Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

 > 장점 : static으로 생성된 변수에 싱글톤 객체를 선언했기 때문에 클래스 로더에 의해 클래스가 로딩 될 때 싱글톤 객체가 생성됩니다. 또 클래스 로더에 의해 클래스가 최초 로딩 될 때 객체가 생성됨으로 Thread-safe합니다.

 > 단점 : 싱글톤 객체를 사용하든 안하든 해당 클래스가 로딩 되는 시점에 항상 싱글톤 객체가 생성(new) 되고 메모리를 차지하고 있으니 비효율적인 방법이 될 수 있습니다.



2. Lazy Initialization (늦은 초기화 방식)

 클래스의 인스턴스가 사용되는 시점에서 싱글톤 객체 생성하는 방식입니다.

public class Singleton {
    private static Singleton instance;
    private Singleton() {  }

    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

 
 > 장점 : 싱글톤 객체가 필요할 때 인스턴스를 얻을 수 있습니다. (Earger initialization 방식에 단점을 보완)
 
 > 단점 : 미Multi-thread 환경에서 여러 곳에서 동시에 getInstance 를 호출할 경우 인스턴스가 두번 생성될 여지가 있습니다. (동기화 문제)



3. Initialization on demand holder idiom (holder에 의한 초기화 방식)

 클래스안에 클래스(Holder)를 두어 JVM의 Class Loader 매커니즘과 Class가 로드되는 시점을 이용한 방식입니다.

public class Singleton {
        // Private constructor prevents instantiation from other classes
        private Singleton() { }

        /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
        private static class SingletonHolder { 
                public static final Singleton INSTANCE = new Singleton();
        }
        public static Singleton getInstance() {
                return SingletonHolder.INSTANCE;
        }
}

Lazy initialization 장점을 가져가면서 Thread간 동기화문제를 동시에 해결한 방법입니다.
(가장 많이 사용되고 있다고 합니다.)



4. Enum Initialization (Enum 초기화 방식)

모든 Enum type 프로그램 내에서 한번 초기화 되는 점을 이용하는 방식입니다.

public enum Singleton {
        INSTANCE;
        public void execute (String arg) {
                //... perform operation here ...
        }
} 

싱글톤의 특징(단 한번의 인스턴스 호출, Thread간 동기화) 을 가지며 비교적 간편하게 사용할 수 있는 방법입니다.
(Joshua Bloch가 작성한 effective java 책에서 소개되었다고 합니다.) 
 
 
 
 
1.Earger initialization
2. Lazy initialization 에 대한 장단점을 이해
3. Initialization on demand holder idiom
4. Enum initialization 활용
특히 Enum 을 활용하는 방법이 흥미가 갑니다:)
 





참조사이트







댓글 1개:

  1. 음.. 4번째 방식인 holder를 이용한 싱글톤 예제를 혹시 만들어주실수 있나요?
    구글링 해도 잘 안나오네요... 초보 개발자는 웁니다 ㅠㅠ

    답글삭제