如何在Android中清除單例例項?
在進入示例之前,我們應該瞭解單例設計模式是什麼。單例是一種設計模式,它將類的例項化限制為只有一個例項。值得注意的用途包括控制併發和建立應用程式訪問其資料儲存的中心訪問點。
此示例演示如何在Android中清除單例例項
步驟 1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必需的詳細資訊以建立新專案。
步驟 2 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://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 = "Clear instance in singleTone" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,我們添加了一個按鈕。當用戶點選“顯示”按鈕時,它將清除單例例項。
步驟 3 - 將以下程式碼新增到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; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { Button show; JSONObject jsonObject; 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.clearInstance(); Toast.makeText(MainActivity.this, "Removed Single tone instance", 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 org.json.JSONObject; import java.util.Arrays; public class singleTonExample { private Context appContext; private Dialog dialog; JSONObject i1; private static 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 clearInstance() { ourInstance = null; } }
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您的一個專案活動檔案,然後單擊執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:
現在點選上面的按鈕,它將清除例項,如下所示:
點選 此處 下載專案程式碼
廣告