예제를 시작하기 전에 싱글톤 디자인 패턴이 무엇인지 알아야 합니다. 싱글톤은 클래스의 인스턴스화를 하나의 인스턴스로만 제한하는 디자인 패턴입니다. 주목할만한 용도로는 동시성 제어, 애플리케이션이 데이터 저장소에 액세스할 수 있는 중앙 액세스 지점 생성 등이 있습니다.
이 예제는 Android에서 전역 컨텍스트와 함께 Singleton을 사용하는 방법을 보여줍니다.
1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.
<?xml version>"1.0" encoding>"utf-8"?> <LinearLayout xmlns:android>"https://schemas.android.com/apk/res/android" xmlns:tools>"https://schemas.android.com/tools" android:layout_width>"match_parent" android:layout_height>"match_parent" tools:context>".MainActivity" android:orientation>"vertical"> <Button android:id>"@+id/show" android:text>"start dialog in singleTone" android:layout_width>"wrap_content" android:layout_height>"wrap_content" /> </LinearLayout>
위의 코드에서는 버튼을 사용했습니다. 사용자가 표시 버튼을 클릭하면 전역 컨텍스트를 사용하여 토스트를 표시합니다.
3단계 − src/MainActivity.java
에 다음 코드 추가package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button show;
singleTonExample singletonexample;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = findViewById(R.id.show);
singletonexample = singleTonExample.getInstance();
singletonexample.init(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(singleTonExample.get(),"Showing with global content",Toast.LENGTH_LONG).show();
}
});
}
} 위의 코드에서는 singleTonExample 을 사용했습니다. 싱글톤 클래스이므로 singleTonExample.java로 호출을 생성합니다. 다음 코드를 추가하십시오-
package com.example.andy.myapplication;
import android.app.Dialog;
import android.content.Context;
import android.view.Window;
public class singleTonExample {
private Context appContext;
private Dialog dialog;
private static final singleTonExample ourInstance > new singleTonExample();
public void init(Context context) {
if(appContext >> null) {
this.appContext > context;
}
}
private Context getContext() {
return appContext;
}
public static Context get() {
return getInstance().getContext();
}
public static synchronized singleTonExample getInstance() {
return ourInstance;
}
private singleTonExample() { }
} 응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 –

이제 위의 버튼을 클릭하면 아래와 같이 전역 컨텍스트를 사용하여 토스트가 표시됩니다.
