Singleton Design [싱글톤 디자인]

  1. Design Object [디자인목적]

    1. 하나의 공통객체 생성이 필요할 때 디자인 적용.
  2. Options [대안들]

    1. static 객체 선언

      -> 선언된 객체가 변경될 수 있다.

  3. Benefit [디자인 장점]

    1. 하나의 공통객체 컨트롤 가능

    2. 싱글톤 객체의 하위객체 제어 가능

    3. 전역변수 사용을 피함으로써 namespace 절약

  4. Structure & Sample Code [구조와 샘플코드]

    싱글톤 클래스 선언

package singleton.improved;

public class Preferences {

    /**
     * 싱글톤 객체 -> static 생성
     * static        -> JVM에 어플리케이션 로드 시 별도의 객체 생성 없이 객체 사용 가능   
     */
    private static Preferences instance = null;

    // Onle access from classes defined in this package
    // Private also possible
    protected Preferences(){};

    // Use synchroized to allow one instance exists among muliy threads
    private synchronized static void createInstance(){
        if(instance == null) instance = new Preferences();
    }

    /**
     * 싱글톤 객체 접근 포인트 -> public 
     */
    public static Preferences getPref(){
        if(instance == null) createInstance();
        return instance;
    }

    public void helloSingleton(){

        System.out.println("Hello i'm a singleton" + instance.toString());
    }    
}

싱글톤 객체의 사용

package singleton.improved;

public class Client {

    public static void main(String[] args) {
        Preferences.getPref().helloSingleton();  //static 선언 객체이기 때문에 별도의 생성 필요 없음
        MyPreferences.getPref().helloSingleton();
    }

}

results matching ""

    No results matching ""