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

โปรแกรม Java ใช้ Private Constructor (Singleton Pattern)


ในบทความนี้ เราจะทำความเข้าใจวิธี ใช้ Private Constructor เพื่อจำกัดการสร้างออบเจกต์ (Restrict Instantiation) และประยุกต์กับ Singleton Design Pattern

Private Constructor คือ Constructor ที่ประกาศด้วยคำว่า private ทำให้ไม่สามารถสร้างออบเจกต์จากภายนอกคลาสได้ (new ClassName() จะ error) ใช้ได้เฉพาะภายในคลาสเดียวกัน

ตัวอย่าง Input และ Output

Input:

Run the program

Output:

Private constructor is being called

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศ Constructor เป็น private
ขั้นตอนที่ 3 - ทำให้ไม่สามารถ new ออบเจกต์จากนอกได้
ขั้นตอนที่ 4 - ใช้ private constructor ร่วมกับ static method ภายในคลาสเดียวกัน
ขั้นตอนที่ 5 - ใช้ร่วมกับ Singleton Pattern เพื่อควบคุมให้มีออบเจกต์เดียว
ขั้นตอนที่ 6 - ใน main เรียก static method เพื่อเข้าถึง private constructor
ขั้นตอนที่ 7 - แสดงผลลัพธ์

ตัวอย่างที่ 1: เรียก Private Constructor ผ่าน Static Method

class PrivateConstructor {
    private PrivateConstructor() {
        System.out.println("A private constructor is being called.");
    }
    public static void instanceMethod() {
        PrivateConstructor my_object = new PrivateConstructor();
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("Invoking a call to private constructor");
        PrivateConstructor.instanceMethod();
    }
}

Output

Invoking a call to private constructor
A private constructor is being called.

ตัวอย่างที่ 2: Singleton Pattern ด้วย Private Constructor

import java.io.*;
class PrivateConstructor {
    static PrivateConstructor instance = null;
    public int my_input = 10;
    private PrivateConstructor() { }
    static public PrivateConstructor getInstance() {
        if (instance == null)
            instance = new PrivateConstructor();
        return instance;
    }
}
public class Main {
    public static void main(String args[]) {
        PrivateConstructor a = PrivateConstructor.getInstance();
        PrivateConstructor b = PrivateConstructor.getInstance();
        a.my_input = a.my_input + 10;
        System.out.println("Invoking a call to private constructor");
        System.out.println("The value of first instance = " + a.my_input);
        System.out.println("The value of second instance = " + b.my_input);
    }
}

Output

Invoking a call to private constructor
The value of first instance = 20
The value of second instance = 20

สังเกต: a และ b อ้างอิงออบเจกต์เดียวกัน (Singleton) ดังนั้นการเปลี่ยนค่า a.my_input ส่งผลต่อ b.my_input ด้วย