0Pricing
Java Academy · บทเรียน

คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static

ออกแบบคลาสอรรถประโยชน์ที่สร้างอินสแตนซ์ไม่ได้ และเปิดให้ใช้เมธอดโรงงานแบบ static แทนตัวสร้าง

คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static เป็นบทเรียน Java Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Java Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Java Academy มีบทเรียนทั้งหมด 4 บทเรียน

คลาสอรรถประโยชน์และเมธอดโรงงานแบบสแตติก

คลาสอรรถประโยชน์มีเมธอดตัวช่วยแบบสแตติกโดยไม่มีสถานะของอินสแตนซ์ ส่วนเมธอดโรงงานแบบสแตติกเป็นทางเลือกที่มีชื่อตั้งให้กับคอนสตรักเตอร์ ซึ่งช่วยให้อ่านง่ายขึ้น รองรับการแคช และมีความยืดหยุ่นมากขึ้น

คลาสอรรถประโยชน์

คลาสอรรถประโยชน์ไม่มีสถานะของอินสแตนซ์ แต่เป็นที่รวมของเมธอดแบบสแตติก ทำให้สร้างอินสแตนซ์ไม่ได้โดยประกาศคอนสตรักเตอร์เป็น private

final class StringUtils {
    // Private constructor prevents instantiation
    private StringUtils() {
        throw new UnsupportedOperationException("Utility class");
    }

    public static boolean isBlank(String s) {
        return s == null || s.strip().isEmpty();
    }

    public static String capitalize(String s) {
        if (isBlank(s)) return s;
        return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();
    }
}

System.out.println(StringUtils.isBlank("  ")); // true
System.out.println(StringUtils.capitalize("hELLO")); // Hello

คลาสอรรถประโยชน์ในไลบรารีมาตรฐาน

ไลบรารีมาตรฐานของ Java เต็มไปด้วยคลาสอรรถประโยชน์ เช่น คลาสสำหรับคอลเลกชัน อาร์เรย์ ออบเจ็กต์ ไฟล์ พาธ และคณิตศาสตร์

import java.util.*;

List<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));

Collections.sort(nums);
System.out.println(nums); // [1, 2, 3, 5, 8, 9]

System.out.println(Collections.min(nums)); // 1
System.out.println(Collections.max(nums)); // 9

Collections.shuffle(nums); // random order

int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 1, 3, 4, 5]
System.out.println(Arrays.binarySearch(arr, 4)); // 3 (index)

เมธอดโรงงานแบบสแตติก

เมธอดโรงงานแบบสแตติกคือเมธอดแบบสแตติกที่มีชื่อและสร้างพร้อมส่งคืนอินสแตนซ์ ประโยชน์ ได้แก่ ชื่อที่สื่อความหมาย สามารถส่งคืนอินสแตนซ์ที่แคชไว้หรืออินสแตนซ์ของชนิดย่อย และสามารถส่งคืนค่า null ได้

class Connection {
    private final String host;
    private final int port;
    private final boolean ssl;

    private Connection(String host, int port, boolean ssl) {
        this.host = host; this.port = port; this.ssl = ssl;
    }

    // Named factory methods — more expressive than constructors
    public static Connection plain(String host) {
        return new Connection(host, 80, false);
    }
    public static Connection secure(String host) {
        return new Connection(host, 443, true);
    }
}
Connection c = Connection.secure("api.example.com");
// Much clearer than: new Connection("api.example.com", 443, true)

การแคชด้วยโรงงานแบบสแตติก

โรงงานแบบสแตติกสามารถส่งคืนอินสแตนซ์ที่แคชไว้ เพื่อหลีกเลี่ยงการจัดสรรซ้ำสำหรับค่าที่ใช้บ่อย (เช่น Integer.valueOf ซึ่งทำเช่นนี้กับค่าตั้งแต่ -128 ถึง 127)

class Color {
    private static final Map<String, Color> CACHE = new HashMap<>();

    public final int r, g, b;

    private Color(int r, int g, int b) {
        this.r = r; this.g = g; this.b = b;
    }

    public static Color of(int r, int g, int b) {
        String key = r + "," + g + "," + b;
        return CACHE.computeIfAbsent(key, k -> new Color(r, g, b));
    }

    public static final Color RED   = of(255, 0, 0);
    public static final Color GREEN = of(0, 255, 0);
    public static final Color BLUE  = of(0, 0, 255);
}
System.out.println(Color.of(255,0,0) == Color.RED); // true (cached)

โรงงานกับคอนสตรักเตอร์: การตั้งชื่อ

แนวทางการตั้งชื่อที่ใช้กันทั่วไปสำหรับเมธอดโรงงานแบบสแตติก:

  • of — โรงงานสำหรับรวมค่า
  • from — โรงงานสำหรับแปลงค่า
  • valueOf — โรงงานสำหรับแปลงค่า (API รุ่นเก่า)
  • getInstance — ซิงเกิลตัน
  • create/newInstance — ออบเจ็กต์ใหม่
  • get — ยืดหยุ่น
// Java API examples:
Optional.of(value)               // of
LocalDate.from(temporal)         // from
Integer.valueOf(42)              // valueOf
Calendar.getInstance()           // getInstance
Array.newInstance(type, length)  // newInstance

// Your own:
HttpRequest.post("https://api.example.com/users")
ApiResponse.error(404, "Not found")
Payment.creditCard("4242...", 9999, "USD")

การส่งคืนชนิดย่อย

เมธอดโรงงานสามารถส่งคืนชนิดย่อยได้ แม้ชนิดค่าที่ประกาศให้ส่งคืนจะเป็นอินเทอร์เฟซ ผู้เรียกจึงไม่ต้องผูกกับการใช้งานรูปธรรม

interface Validator<T> {
    boolean validate(T value);
    String errorMessage();
}

class EmailValidator implements Validator<String> {
    public boolean validate(String email) { return email.contains("@"); }
    public String errorMessage() { return "Invalid email address"; }
}

class Validators {
    // Returns interface type — hides implementation
    public static Validator<String> email() { return new EmailValidator(); }
    public static Validator<String> notBlank() {
        return new Validator<>() {
            public boolean validate(String s) { return s != null && !s.isBlank(); }
            public String errorMessage() { return "Value required"; }
        };
    }
}

Builder ผ่านโรงงานแบบสแตติก

ผสานคอนสตรักเตอร์แบบ private เข้ากับโรงงานแบบสแตติกและ Builder ที่ซ้อนอยู่ภายใน เพื่อสร้างออบเจ็กต์ที่ซับซ้อน

class EmailMessage {
    private final String to, subject, body;
    private final boolean html;

    private EmailMessage(Builder b) {
        this.to = b.to; this.subject = b.subject;
        this.body = b.body; this.html = b.html;
    }

    public static Builder builder(String to) { return new Builder(to); }

    public static class Builder {
        private final String to;
        private String subject = "", body = "";
        private boolean html = false;

        Builder(String to) { this.to = to; }
        public Builder subject(String s) { this.subject = s; return this; }
        public Builder body(String b) { this.body = b; return this; }
        public Builder html() { this.html = true; return this; }
        public EmailMessage build() { return new EmailMessage(this); }
    }
}
EmailMessage.builder("alice@co.com").subject("Welcome!").html().build();

การตรวจสอบความถูกต้องในเมธอดโรงงาน

เมธอดโรงงานเหมาะอย่างยิ่งสำหรับตรวจสอบอินพุตก่อนสร้างออบเจ็กต์ — ให้โยนข้อยกเว้นที่สื่อความหมายพร้อมข้อมูลบริบท

class PortNumber {
    private final int value;

    private PortNumber(int value) { this.value = value; }

    public static PortNumber of(int port) {
        if (port < 1 || port > 65535)
            throw new IllegalArgumentException(
                "Port must be 1-65535, got: " + port);
        return new PortNumber(port);
    }

    public static PortNumber http()  { return new PortNumber(80); }
    public static PortNumber https() { return new PortNumber(443); }

    public int value() { return value; }
    public boolean isPrivileged() { return value < 1024; }
}
System.out.println(PortNumber.https().isPrivileged()); // true

API คอลเลกชัน: โรงงานแบบสแตติก

Java 9 ขึ้นไปเพิ่ม List.of(), Set.of(), Map.of() ซึ่งเป็นเมธอดโรงงานแบบสแตติกสำหรับสร้างคอลเลกชันที่เปลี่ยนแปลงไม่ได้

import java.util.*;

List<String> fruits = List.of("Apple", "Banana", "Cherry");
Set<Integer> ids    = Set.of(1, 2, 3, 4, 5);
Map<String, Integer> ages = Map.of("Alice", 30, "Bob", 25);

// All are unmodifiable:
try {
    fruits.add("Durian"); // UnsupportedOperationException
} catch (UnsupportedOperationException e) {
    System.out.println("Cannot modify!");
}

// Map.entry and Map.ofEntries for > 10 entries
Map<String, String> config = Map.ofEntries(
    Map.entry("host", "localhost"),
    Map.entry("port", "8080")
);

เมื่อใดควรเลือกใช้เมธอดโรงงาน

ควรเลือกใช้เมธอดโรงงานแบบสแตติกแทนคอนสตรักเตอร์เมื่อ:

  • คุณต้องการชื่อที่สื่อความหมาย
  • โรงงานอาจส่งคืนอินสแตนซ์ที่แคชไว้หรืออินสแตนซ์ของชนิดย่อย
  • จำเป็นต้องตรวจสอบความถูกต้องก่อนการสร้าง
  • คุณต้องการควบคุมจำนวนอินสแตนซ์ (ซิงเกิลตัน พูล)
// Constructor: hard to know what this means
new Complex(0.5, -1.2);

// Factory: clear meaning
Complex.fromPolar(1.3, Math.PI / 4); // polar form
Complex.rectangular(0.5, -1.2);      // rectangular form

// Constructor: no caching
new Boolean(true); // deprecated — creates new object!

// Factory: returns cached instance (Boolean.TRUE or FALSE)
Boolean.valueOf(true); // returns Boolean.TRUE singleton

ตรวจสอบความเข้าใจอย่างรวดเร็ว

ข้อได้เปรียบหลักของเมธอดโรงงานแบบสแตติกเมื่อเทียบกับคอนสตรักเตอร์สาธารณะคืออะไร

สรุป: คลาสอรรถประโยชน์และเมธอดโรงงานแบบสแตติก

ประเด็นสำคัญ:

  • คลาสอรรถประโยชน์: คลาส final ที่มีคอนสตรักเตอร์เป็น private และมีเมธอดแบบสแตติกทั้งหมด
  • เมธอดโรงงานแบบสแตติกเป็นทางเลือกที่มีชื่อตั้งให้กับคอนสตรักเตอร์
  • ชื่อที่ใช้กันทั่วไป: of, from, valueOf, getInstance, create, newInstance
  • โรงงานสามารถส่งคืนอินสแตนซ์ที่แคชไว้ได้ — ดู Integer.valueOf(-128..127)
  • โรงงานสามารถส่งคืนชนิดย่อยพร้อมซ่อนการใช้งานรูปธรรม
  • ใช้ตัวสร้างภายในโรงงานสำหรับการสร้างออบเจ็กต์ที่มีพารามิเตอร์หลายตัวและซับซ้อน

คำถามที่พบบ่อย

บทเรียน “คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Java Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Java Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static”

ออกแบบคลาสอรรถประโยชน์ที่สร้างอินสแตนซ์ไม่ได้ และเปิดให้ใช้เมธอดโรงงานแบบ static แทนตัวสร้าง คุณปฏิบัติ Java Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Java Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Java Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Java Academy นี้ได้ไหม

ได้ บทเรียน Java Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. กฎการโอเวอร์โหลดเมธอด
  2. พารามิเตอร์ Varargs
  3. ฟิลด์แบบ Static และค่าคงที่
  4. คลาสอรรถประโยชน์และเมธอดโรงงานแบบ Static
← กลับไปที่ Java Academy