Android의 싱글 톤
이 링크를 따라 Android에서 싱글 톤 클래스를 성공적으로 만들었습니다. http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/
문제는 내가 단일 객체를 원한다는 것입니다. 활동 A와 활동 B가 있습니다. 활동 AI에서 Singleton의 개체에 액세스합니다 class
. 개체를 사용하고 일부 변경했습니다.
활동 B로 이동하고 싱글 톤 클래스에서 객체에 액세스하면 초기화 된 객체를 제공하고 활동 A에서 변경 한 내용을 유지하지 않습니다. 변경 사항을 저장할 다른 방법이 있습니까? 전문가를 도와주세요. 이것은MainActivity
public class MainActivity extends Activity {
protected MyApplication app;
private OnClickListener btn2=new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent=new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get the application instance
app = (MyApplication)getApplication();
// Call a custom application method
app.customAppMethod();
// Call a custom method in MySingleton
Singleton.getInstance().customSingletonMethod();
Singleton.getInstance();
// Read the value of a variable in MySingleton
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(btn2);
}
}
이것은 NextActivity
public class NextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String singletonVar = Singleton.customVar;
Log.d("Test",singletonVar);
}
}
Singleton
수업
public class Singleton
{
private static Singleton instance;
public static String customVar="Hello";
public static void initInstance()
{
if (instance == null)
{
// Create the instance
instance = new Singleton();
}
}
public static Singleton getInstance()
{
// Return the instance
return instance;
}
private Singleton()
{
// Constructor hidden because this is a singleton
}
public void customSingletonMethod()
{
// Custom method
}
}
과 MyApplication
public class MyApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
// Initialize the singletons so their instances
// are bound to the application process.
initSingletons();
}
protected void initSingletons()
{
// Initialize the instance of MySingleton
Singleton.initInstance();
}
public void customAppMethod()
{
// Custom application method
}
}
이 코드를 실행하면 Singleton
내가 준 World 에서 초기화 한 MainActivity
Hello가 표시되고 다시 NextActivity
logcat에 Hello가 표시 됩니다. 에서 다시 세계를 보여주고 싶습니다 NextActivity
. 이 문제를 해결하도록 도와주세요.
편집하다 :
Android에서 Singleton의 구현은 "안전"하지 않으며 ( 여기 참조 ) Dagger 또는 기타 DI 라이브러리 와 같은 이러한 종류의 패턴 전용 라이브러리를 사용하여 수명주기 및 삽입을 관리해야합니다.
코드에서 예제를 게시 할 수 있습니까?
이 요점을 살펴보십시오 : https://gist.github.com/Akayh/5566992
작동하지만 매우 빠르게 완료되었습니다.
MyActivity : 처음으로 싱글 톤을 설정하고 개인 생성자에서 mString 속성 ( "Hello")을 초기화하고 값 ( "Hello")을 표시합니다.
새 값을 mString : "Singleton"으로 설정합니다.
activityB를 시작하고 mString 값을 표시합니다. "싱글턴"이 나타납니다 ...
팁 : 싱글 톤 클래스를 만들려면 Android Studio에서 프로젝트를 마우스 오른쪽 버튼으로 클릭하고 메뉴를 엽니 다.
New -> Java Class -> Choose Singleton from dropdown menu
Java로서 Android도 싱글 톤을 지원하는 것은 간단합니다. -
Singleton은 Gang of Four 디자인 패턴의 일부이며 창작 디자인 패턴으로 분류됩니다.
-> 정적 멤버 : 싱글 톤 클래스의 인스턴스를 포함합니다.
-> 개인 생성자 : 다른 사람이 Singleton 클래스를 인스턴스화하는 것을 방지합니다.
-> Static public method : Singleton 객체에 대한 전역 액세스 지점을 제공하고 클라이언트 호출 클래스에 인스턴스를 반환합니다.
- 개인 인스턴스 생성
- 개인 생성자 생성
Singleton 클래스의 getInstance () 사용
public class Logger{ private static Logger objLogger; private Logger(){ //ToDo here } public static Logger getInstance() { if (objLogger == null) { objLogger = new Logger(); } return objLogger; } }
싱글 톤을 사용하는 동안-
Logger.getInstance();
rakesh가 제안한 답변은 훌륭하지만 여전히 Android의 Singleton은 Java의 Singleton과 동일합니다. Singleton 디자인 패턴은 이러한 모든 문제를 해결합니다. Singleton 디자인 패턴으로 다음을 수행 할 수 있습니다.
1) 클래스의 인스턴스가 하나만 생성되었는지 확인
2) 객체에 대한 글로벌 액세스 지점 제공
3) 싱글 톤 클래스의 클라이언트에 영향을주지 않고 향후 여러 인스턴스 허용
기본 Singleton 클래스 예 :
public class MySingleton
{
private static MySingleton _instance;
private MySingleton()
{
}
public static MySingleton getInstance()
{
if (_instance == null)
{
_instance = new MySingleton();
}
return _instance;
}
}
이 답변 에서 @Lazy가 언급했듯이 Android Studio의 템플릿에서 싱글 톤을 만들 수 있습니다. 정적 ourInstance
변수가 먼저 초기화 되므로 인스턴스가 null인지 확인할 필요가 없습니다 . 결과적으로 Android Studio에서 만든 싱글 톤 클래스 구현은 다음 코드처럼 간단합니다.
public class MySingleton {
private static MySingleton ourInstance = new MySingleton();
public static MySingleton getInstance() {
return ourInstance;
}
private MySingleton() {
}
}
You are copying singleton's customVar
into a singletonVar
variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
I put my version of Singleton below:
public class SingletonDemo {
private static SingletonDemo instance = null;
private static Context context;
/**
* To initialize the class. It must be called before call the method getInstance()
* @param ctx The Context used
*/
public static void initialize(Context ctx) {
context = ctx;
}
/**
* Check if the class has been initialized
* @return true if the class has been initialized
* false Otherwise
*/
public static boolean hasBeenInitialized() {
return context != null;
}
/**
* The private constructor. Here you can use the context to initialize your variables.
*/
private SingletonDemo() {
// Use context to initialize the variables.
}
/**
* The main method used to get the instance
*/
public static synchronized SingletonDemo getInstance() {
if (context == null) {
throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before");
}
if (instance == null) {
instance = new SingletonDemo();
}
return instance;
}
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException("Clone is not allowed.");
}
}
Note that the method initialize could be called in the main class(Splash) and the method getInstance could be called from other classes. This will fix the problem when the caller class requires the singleton but it does not have the context.
Finally the method hasBeenInitialized is uses to check if the class has been initialized. This will avoid that different instances have different contexts.
Android에서 싱글 톤을 사용하는 가장 깨끗하고 현대적인 방법 은 Dagger 2 라는 종속성 주입 프레임 워크 를 사용하는 것 입니다. 여기에서 사용할 수있는 가능한 범위에 대한 설명이 있습니다. Singleton은 이러한 범위 중 하나입니다. 의존성 주입은 그렇게 쉽지는 않지만 이해하는 데 약간의 시간을 투자해야합니다. 또한 테스트가 더 쉬워집니다.
참고 URL : https://stackoverflow.com/questions/16517702/singleton-in-android
'Program Tip' 카테고리의 다른 글
플롯 창이 응답하지 않음 (0) | 2020.10.31 |
---|---|
OpenSubKey ()는 regedit.exe에서 볼 수있는 레지스트리 키에 대해 null을 반환합니다. (0) | 2020.10.31 |
ASP.NET 5 MVC 6 (vNext)에서 ID에 대한 암호 규칙을 어떻게 정의합니까? (0) | 2020.10.31 |
문자열 또는 정수로 열거 형 값을 얻는 방법 (0) | 2020.10.31 |
토큰 기반 인증을위한 JWT 대 쿠키 (0) | 2020.10.31 |