Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 싱글톤(Singleton) 클래스를 사용하는 방법


예제를 살펴보기에 앞서, 싱글톤 디자인 패턴이 무엇인지 먼저 이해할 필요가 있습니다. 싱글톤(Singleton)은 하나의 클래스에 대해 인스턴스 생성을 단 하나로 제한하는 디자인 패턴입니다. 대표적인 활용 사례로는 동시성(Concurrency) 제어와, 애플리케이션 전체가 데이터 저장소에 접근할 수 있는 중앙 접점(Central Point of Access)을 만드는 것이 있습니다.

이 글에서는 안드로이드에서 싱글톤 클래스를 실제로 구현하고 사용하는 방법을 단계별로 알아보겠습니다.

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">
    <EditText
        android:id = "@+id/editText"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:hint = "Enter text" />
    <Button
        android:id = "@+id/save"
        android:text = "save in singleTone"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 코드에는 EditTextButton이 포함되어 있습니다. 사용자가 버튼을 클릭하면 EditText에 입력된 텍스트를 가져와 싱글톤 클래스에 저장하고, 이어서 싱글톤 클래스에서 값을 읽어 토스트(Toast) 메시지로 화면에 표시하게 됩니다.

3단계: MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button save;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        save = findViewById(R.id.save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText.getText().toString().isEmpty()) {
                    editText.setError("Enter text");
                }else{
                    String editValue = editText.getText().toString();
                    singleTonExample singletonexample = com.example.andy.myapplication.singleTonExample.getInstance();
                    singletonexample.setText(editValue);
                    Toast.makeText(MainActivity.this,singletonexample.getText(),Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}

위 코드에서는 singleTonExample을 싱글톤 클래스로 사용했습니다. 이제 singleTonExample.java 파일을 새로 생성하고 아래 코드를 추가합니다.

4단계: 싱글톤 클래스 구현

package com.example.andy.myapplication;
import java.security.Identity;
public class singleTonExample {
    String editValue;
    private static final singleTonExample ourInstance = new singleTonExample();
    public static singleTonExample getInstance() {
        return ourInstance;
    }
    private singleTonExample() { }
    public void setText(String editValue) {
        this.editValue = editValue;
    }
    public String getText() {
        return editValue;
    }
}

싱글톤 패턴의 핵심 요소가 모두 담겨 있는 코드입니다. 정적(static) 변수 ourInstance에 유일한 인스턴스를 미리 생성해 두고, getInstance() 메서드를 통해서만 해당 인스턴스에 접근할 수 있도록 합니다. 또한 생성자를 private으로 선언함으로써 외부에서 new 키워드로 인스턴스를 추가로 생성하는 것을 차단합니다. 이것이 바로 "클래스의 인스턴스를 하나만 유지한다"는 싱글톤 패턴의 본질입니다.

애플리케이션 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기에 앱의 기본 화면이 표시됩니다.

안드로이드에서 싱글톤(Singleton) 클래스를 사용하는 방법

위 결과 화면에서 "tutorialspoint.com"이라는 텍스트를 입력했습니다. 이제 버튼을 클릭하면 싱글톤 클래스에 저장된 데이터를 가져와 아래와 같이 토스트 메시지로 출력합니다.

안드로이드에서 싱글톤(Singleton) 클래스를 사용하는 방법

이처럼 싱글톤 패턴을 활용하면 액티비티나 프래그먼트 간에 데이터를 손쉽게 공유할 수 있으며, 애플리케이션 전역에서 일관된 상태를 유지하는 데 큰 도움이 됩니다.