一手遮天 Android - 设计模式: Singleton(单例模式)
一手遮天 Android - 设计模式: Singleton(单例模式)
示例如下:
/designpattern/Singleton.java
/**
* 单例模式的调用示例
*/
package com.webabcd.androiddemo.designpattern;
import android.os.SystemClock;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.webabcd.androiddemo.R;
public class Singleton extends AppCompatActivity {
private TextView mTextView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_designpattern_singleton);
mTextView1 = findViewById(R.id.textView1);
sample();
}
private void sample() {
mTextView1.append(String.valueOf(SingletonPattern.getInstance().getTimestamp()));
SystemClock.sleep(100);
mTextView1.append("\n");
mTextView1.append(String.valueOf(SingletonPattern.getInstance().getTimestamp()));
}
}
\designpattern\SingletonPattern.java
/**
* 单例模式
*/
package com.webabcd.androiddemo.designpattern;
import android.os.SystemClock;
public class SingletonPattern {
private static SingletonPattern instance = null;
public synchronized static SingletonPattern getInstance() {
if (instance == null) {
instance = new SingletonPattern();
}
return instance;
}
private final long mTimestamp;
private SingletonPattern() {
mTimestamp = SystemClock.elapsedRealtime();
}
public long getTimestamp() {
return mTimestamp;
}
}
/layout/activity_designpattern_singleton.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>