예제에 들어가기 전에 싱글톤 디자인 패턴이 무엇인지 알아야 합니다. 싱글톤은 클래스의 인스턴스화를 하나의 인스턴스로만 제한하는 디자인 패턴입니다. 주목할만한 용도로는 동시성을 제어하고 애플리케이션이 데이터 저장소에 액세스할 수 있도록 중앙 액세스 지점을 만드는 것이 있습니다.
이 예제는 Android에서 싱글톤 클래스를 사용하는 방법을 보여줍니다.
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"> <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>
위의 코드에서 우리는 편집 Ext와 버튼을 취했습니다. 사용자가 버튼을 클릭하면 편집 텍스트에서 데이터를 가져와 싱글톤 클래스에 저장하고 토스트에 싱글톤 클래스의 값을 표시합니다.
3단계 − 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로 호출을 생성하고 다음 코드를 추가합니다-
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;
}
} 응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 –

위의 결과에서 우리는 tutorialspoint.com으로 작성했습니다." 이제 버튼을 클릭하면 싱글톤 클래스에서 데이터를 가져와 아래와 같이 토스트에 표시합니다. –
