Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng Singleton với Global Context trong Android

Giới thiệu về Singleton Pattern

Singleton là một mẫu thiết kế (design pattern) giới hạn việc khởi tạo một lớp chỉ có một thể hiện duy nhất. Các trường hợp sử dụng phổ biến bao gồm kiểm soát đồng thời (concurrency) và tạo một điểm truy cập trung tâm để ứng dụng truy cập kho dữ liệu của nó.

Ví dụ: Singleton với Global Context

Ví dụ này minh họa cách triển khai Singleton để lưu trữ Context toàn cục (Global Context) trong Android.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền các thông tin cần thiết để tạo dự án mới.

Bước 2: Thiết kế giao diện (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">

    <Button
        android:id="@+id/show"
        android:text="Hiển thị Toast từ Singleton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Giao diện chỉ chứa một nút bấm. Khi người dùng nhấn nút này, ứng dụng sẽ hiển thị Toast sử dụng Global Context từ Singleton.

Bước 3: MainActivity.java

package com.example.singletonexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button btnShow;
    SingleTonExample singletonExample;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnShow = findViewById(R.id.show);
        singletonExample = SingleTonExample.getInstance();
        singletonExample.init(getApplicationContext());

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(SingleTonExample.get(), "Hiển thị với Global Context", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Bước 4: Lớp Singleton (SingleTonExample.java)

package com.example.singletonexample;

import android.content.Context;

public class SingleTonExample {
    private Context appContext;
    private static final 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() { }
}

Chạy ứng dụng

Kết nối thiết bị Android thật với máy tính. Trong Android Studio, mở file Activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn làm mục tiêu triển khai.

Màn hình mặc định sẽ hiển thị nút bấm. Nhấn nút để xem Toast hiển thị bằng Global Context từ Singleton.

Lưu ý quan trọng

  • Sử dụng getApplicationContext() thay vì this (Activity Context) để tránh rò rỉ bộ nhớ (memory leak).
  • Phương thức init() chỉ gán context lần đầu tiên (kiểm tra null) để đảm bảo tính bất biến.
  • Singleton này phù hợp cho các trường hợp cần Context toàn cục như hiển thị Toast, truy cập SharedPreferences, hoặc khởi tạo thư viện bên thứ ba.