Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีใช้ Singleton กับ Global Context ใน Android

ภาพรวมของ Singleton Design Pattern

Singleton เป็นรูปแบบการออกแบบ (Design Pattern) ที่จำกัดการสร้างอินสแตนซ์ของคลาสให้มีเพียงอินสแตนซ์เดียวเท่านั้น การใช้งานที่น่าสนใจรวมถึงการควบคุมการทำงานแบบขนาน (Concurrency) และการสร้างจุดเข้าถึงศูนย์กลางสำหรับแอปพลิเคชันเพื่อเข้าถึงที่เก็บข้อมูล

ตัวอย่าง: การใช้ Singleton กับ Global Context

ตัวอย่างนี้สาธิตวิธีใช้งาน Singleton พร้อม Global Context ใน Android เพื่อแสดง Toast โดยใช้ Context แบบ Global

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio → File → New Project → กรอกรายละเอียดที่จำเป็นเพื่อสร้างโปรเจกต์ใหม่

ขั้นตอนที่ 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">

    <Button
        android:id="@+id/show"
        android:text="เริ่ม Dialog ใน Singleton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

ในโค้ดด้านบน เราได้วางปุ่ม (Button) เมื่อผู้ใช้คลิกปุ่ม Show จะแสดง Toast โดยใช้ Global Context

ขั้นตอนที่ 3: เขียนโค้ด MainActivity (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;

public class MainActivity extends AppCompatActivity {
    Button show;
    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) {
                Toast.makeText(SingleTonExample.get(), "แสดงด้วย Global Context", Toast.LENGTH_LONG).show();
            }
        });
    }
}

ขั้นตอนที่ 4: สร้างคลาส Singleton (SingleTonExample.java)

package com.example.andy.myapplication;

import android.app.Dialog;
import android.content.Context;
import android.view.Window;

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

การทดสอบแอปพลิเคชัน

เชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์ ใน Android Studio เปิดไฟล์ Activity และคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณ จากนั้นตรวจสอบหน้าจอเริ่มต้น

วิธีใช้ Singleton กับ Global Context ใน Android

คลิกปุ่มด้านบน จะแสดง Toast โดยใช้ Global Context ตามภาพด้านล่าง

วิธีใช้ Singleton กับ Global Context ใน Android

หมายเหตุสำคัญ

  • ใช้ getApplicationContext() เพื่อให้ได้ Context ที่มีอายุการใช้งานตลอดชีวิตของแอป ป้องกัน Memory Leak
  • การตรวจสอบ if (appContext == null) ป้องกันการเขียนทับ Context เดิม
  • ควรพิจารณาใช้ Dependency Injection (เช่น Hilt, Koin) แทน Singleton สำหรับโปรเจกต์ขนาดใหญ่