본격적인 예제에 앞서 싱글턴(Singleton) 디자인 패턴이 무엇인지 간단히 짚고 넘어가겠습니다. 싱글턴은 하나의 클래스에 대해 인스턴스 생성을 단 하나로 제한하는 디자인 패턴입니다. 대표적인 활용 사례로는 동시성(concurrency) 제어와, 애플리케이션 전체에서 데이터 저장소에 접근할 수 있는 중앙 집중식 진입점을 만드는 것이 있습니다.
이번 예제에서는 안드로이드에서 전역 컨텍스트(Global Context)와 함께 배열을 싱글턴 객체에 저장하는 방법을 단계별로 알아봅니다.
1단계 – 새 프로젝트 생성
Android Studio에서 새 프로젝트를 만듭니다. 상단 메뉴에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.
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 = "save array in singleTone"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content" />
</LinearLayout>위 코드에는 버튼 하나가 배치되어 있습니다. 사용자가 이 버튼을 클릭하면 싱글턴에 저장된 배열 값이 토스트(Toast) 메시지로 화면에 표시됩니다.
3단계 – MainActivity.java 코드 추가
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;
int[] i1 = new int[] { 33, 12, 98 };
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.storeArray(i1);
Toast.makeText(singleTonExample.get(),singletonexample.getArray(),
Toast.LENGTH_LONG).show();
}
});
}
}위 코드에서는 singleTonExample을 싱글턴 클래스로 사용했습니다. 따라서 singleTonExample.java라는 이름의 새 클래스를 생성하고 아래 코드를 추가합니다.
package com.example.andy.myapplication;
import android.app.Dialog;
import android.content.Context;
import android.view.Window;
import java.util.Arrays;
public class singleTonExample {
private Context appContext;
private Dialog dialog;
int[] i1;
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() { }
public void show(Context context) {
if (dialog != null && dialog.isShowing()) {
return;
}
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.layout_progress_dialog);
dialog.setCancelable(true);
dialog.show();
}
public void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void storeArray(int[] i1) {
this.i1 = i1;
}
public String getArray() {
return Arrays.toString(i1);
}
}핵심 포인트 정리
- 전역 컨텍스트 사용: 싱글턴에 Context를 저장할 때는 반드시
getApplicationContext()를 사용해야 합니다. Activity나 Fragment의 컨텍스트를 그대로 저장하면 해당 컴포넌트가 종료된 후에도 참조가 유지되어 메모리 누수(memory leak)가 발생할 수 있습니다. - 중복 초기화 방지:
init()메서드에서appContext가 null일 때만 값을 할당함으로써, 여러 액티비티에서 호출되더라도 컨텍스트가 불필요하게 교체되지 않도록 합니다. - 배열 저장 및 조회:
storeArray()로 배열을 저장하고,getArray()에서Arrays.toString()을 활용해 배열 내용을 문자열로 변환하여 손쉽게 출력할 수 있습니다.
애플리케이션 실행
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 나타납니다.

이제 화면의 버튼을 클릭하면, 전역 컨텍스트를 통해 싱글턴에 저장된 배열 값이 토스트 메시지로 표시됩니다.
