2014-11-26 1 views
1

내 애플리케이션에서 사용하는 다양한 서체를 저장하기 위해 Android 애플리케이션에서 내 애플리케이션을 확장했습니다. 모든 것은 잘 작동하지만 코드의 싱글 톤 부분을 이해하지 못하고 getInstance의 목표는 무엇입니까 (나는 중단 점을 설정하고 절대로 호출되지 않습니다. 또한 응용 프로그램의 메서드 이름을 바꿀 때도 호출되지 않습니다. 잘). 누군가이 패턴에 대해 나에게 계몽 수 있을까요? 나는 보통 OOP로 일하지 않기 때문에 어리석은 질문 일 수있다.Android 확장 애플리케이션 패턴 의심

MyApplication.java

public class MyApplication extends Application { 
    private Typeface _typefaceNormal; 
    private Typeface _typefaceBold; 

    private static MyApplication singleton; 

    public MyApplication getInstance() { 
     return singleton; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     singleton = this; 
     this._typefaceNormal = Typeface.createFromAsset(getAssets(),"PTS55F.TTF"); 
     this._typefaceBold = Typeface.createFromAsset(getAssets(), "PTS75F.TTF"); 
    } 

    public Typeface getNormalFont() { 
     return this._typefaceNormal; 
     // return this._typefaceNormal; 
    } 

    public Typeface getBoldFont() { 
     return this._typefaceBold; 
     // return this._typefaceBold; 
    } 
} 

그리고 내가 만드는이 같은 전화 :

this._typeface = ((MyApplication) _activity.getApplicationContext()).getNormalFont(); 

편집 내가 수집 한 답변에서

, 일부 추가 연구, 이것은 제가 사용을 끝낸 클래스였습니다 :

,210
public class MyGlobalConfig { 
    private static MyGlobalConfig singleton; 
    private Typeface _typefaceNormal; 
    private Typeface _typefaceBold; 

    private MyGlobalConfig() { 

    } 

    public static MyGlobalConfig getInstance() { 
     if (singleton == null) { 
      singleton = new MyGlobalConfig(); 
     } 
     return singleton; 
    } 

    public void init(Context ctx, String typefaceNormal, String typefaceBold) { 
     this._typefaceNormal = Typeface.createFromAsset(ctx.getAssets(), 
       typefaceNormal); 
     this._typefaceBold = Typeface.createFromAsset(ctx.getAssets(), 
       typefaceBold); 
    } 

    public Typeface getNormalFont() { 
     return this._typefaceNormal; 
     // return this._typefaceNormal; 
    } 

    public Typeface getBoldFont() { 
     return this._typefaceBold; 
     // return this._typefaceBold; 
    } 
} 

나는 그것을 초기화 :

MyGlobalConfig.getInstance().init(getApplicationContext(), normalFont, boldFont); 

그리고 나의 글꼴을 설정

MyGlobalConfig.getInstance().getNormalFont(); 
+0

내가 아는 한, 당신은 (아마도) 당신이 동시에 두 개의 응용 프로그램을 실행하지 않기 때문에 여기에 싱글 톤이 필요하지 않습니다. – guness

+0

'Application' * IS * 싱글 톤 - 하나의 인스턴스 만 존재합니다. 또한, 서체를 검색하는 것과 같이 사소한 일을하기 위해'Application'을 확장하지 마십시오. – Squonk

+0

@Squonk 그래서 기준은 무엇입니까? 나는 그 이후로 안드로이드가 왜 서체를 프로그래밍 방식으로 바꿀 수 있는지, 그리고 "setTypeFace"를 많이 사용했기 때문에 안드로이드는 전역 변수로 저장할 좋은 장소가 될 것이라고 생각했다. – Bernardo

답변

2
싱글 톤 패턴의 목적은 클래스의 하나의 인스턴스가 생성 될 수 있음을 시행하는 것입니다

. 당신은 실제로 그것을 여기에서 달성하지 않습니다. Java에서이 작업을 수행하는 적절한 방법은 생성자를 private로 설정 한 다음 정적 변수를 클래스의 단일 인스턴스로 설정하는 것입니다. 예 :

public class MySingletonClass{ 
    private static MySingletonClass singleton; 

    // private constructor 
    private MySingletonClass(){} 

    public static MySingletonClass getInstance(){ 
    if(singleton == null){ 
    singleton = new MySingletonClass(); 
    } 
    return singleton; 
    } 
} 

Android로 작업 할 때는 Application 클래스를 싱글 톤으로 만들 필요가 없습니다. Android는 하나의 인스턴스 만 만들고 관리합니다. 또한 Application 클래스에는 이미 public 생성자가 정의되어 있으므로 컴파일러에서 확장 클래스에서 생성자를 private으로 설정할 수는 없으므로 singleton 패턴을 적용 할 수 없다고 생각합니다.

+0

오 오케이 ... 이제 말이됩니다. 내 코드는 다양한 Google 검색 그룹이지만 결코 사용되지 않은 getInstances를 많이 보았습니다. 이유를 알고 싶습니다. 그러나 설명에 대해 대단히 감사합니다. 그것은 완벽한 의미를가집니다. :) – Bernardo

1

정적 메서드 MyApplication.getInstance()를 사용하지 않았기 때문입니다. 대신 context.getApplicationContext()를 통해 참조에 액세스합니다.이 경우 "singleton"정적 변수와 동일한 참조가됩니다.

static 메소드 getInstance()를 통해 인스턴스에 액세스하면 컨텍스트 참조없이 액세스하여 casting ((MyApplication) _activity.getApplicationContext())에서 사용자를 저장할 수 있습니다. 나쁜 측면에서, 그것은 당신의 코드를 결합하고 덜 testable합니다.