예제에 들어가기 전에 싱글톤 디자인 패턴이 무엇인지 알아야 합니다. 싱글톤은 클래스의 인스턴스화를 하나의 인스턴스로만 제한하는 디자인 패턴입니다. 주목할만한 용도로는 동시성 제어, 애플리케이션이 데이터 저장소에 액세스할 수 있는 중앙 액세스 지점 생성 등이 있습니다.
이 예제는 Android에서 Singleton Alert Dialog를 사용하는 방법을 보여줍니다.
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 = "Alert Dialog from 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;
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) {
singletonexample.AlertDialog(MainActivity.this);
}
});
}
} 위의 코드에서는 singleTonExample 을 사용했습니다. 싱글톤 클래스이므로 singleTonExample.java로 호출을 생성합니다. 다음 코드를 추가하십시오-
package com.example.andy.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
public class singleTonExample {
static TextToSpeech t1;
private static singleTonExample ourInstance = new singleTonExample();
private Context appContext;
private singleTonExample() { }
public static Context get() {
return getInstance().getContext();
}
public static synchronized singleTonExample getInstance() {
return ourInstance;
}
public void init(Context context) {
if (appContext = = null) {
this.appContext = context;
}
}
private Context getContext() {
return appContext;
}
public void AlertDialog(final MainActivity mainActivity) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mainActivity);
alertDialogBuilder.setMessage("Are you sure, You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(mainActivity, "You clicked yes button", Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mainActivity.finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
} 응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 –

이제 위의 버튼을 클릭하면 아래와 같이 싱글톤 클래스의 경고 대화 상자가 표시됩니다. -.
