Singleton และ Factory Method
นำรูปแบบ Singleton มาใช้เพื่อสร้างอินสแตนซ์ที่ไม่ซ้ำกัน และใช้ Factory Method เพื่อสร้างออบเจ็กต์ได้อย่างยืดหยุ่น
Singleton และ Factory Method เป็นบทเรียน Clean Architecture & Design Patterns in Practice ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Clean Architecture & Design Patterns in Practice และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Intro to Creational Patterns
Welcome to our lesson on Creational Design Patterns! These patterns are all about how objects are created.
They help us manage object instantiation in a way that makes our systems more flexible and robust. Instead of directly creating objects everywhere, we use patterns to control this process.
Singleton: One Instance Only
The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
- It's useful for resources that should be unique, like a configuration manager or a logger.
- To achieve this, the class typically has a private constructor and a static method that returns the single instance.
Building a Basic Singleton
Here's a simple example of a Singleton. Notice the private constructor and the static getInstance() method.
The getInstance() method checks if an instance already exists; if not, it creates one. Otherwise, it returns the existing one.
public class SimpleLogger {
private static SimpleLogger instance;
// Private constructor to prevent direct instantiation
private SimpleLogger() {
System.out.println("SimpleLogger instance created!");
}
public static SimpleLogger getInstance() {
if (instance == null) {
instance = new SimpleLogger();
}
return instance;
}
public void log(String message) {
System.out.println("LOG: " + message);
}
}
public class Main {
public static void main(String[] args) {
SimpleLogger logger1 = SimpleLogger.getInstance();
logger1.log("Application starting up.");
SimpleLogger logger2 = SimpleLogger.getInstance();
logger2.log("Processing user request.");
if (logger1 == logger2) {
System.out.println("Both logger references point to the same instance!");
}
}
}Singleton: Thread-Safe Access
The basic Singleton can have issues in multi-threaded environments. If multiple threads call getInstance() at the same time when instance is null, more than one instance could be created.
We can make it thread-safe by using the synchronized keyword on the getInstance() method. This ensures only one thread can execute it at a time.
public class ThreadSafeLogger {
private static ThreadSafeLogger instance;
private ThreadSafeLogger() {
System.out.println("ThreadSafeLogger instance created!");
}
public static synchronized ThreadSafeLogger getInstance() {
if (instance == null) {
instance = new ThreadSafeLogger();
}
return instance;
}
public void log(String message) {
System.out.println("TS_LOG: " + message);
}
}
public class Main {
public static void main(String[] args) {
// In a real app, threads would access this concurrently.
// Here, we just show it works correctly sequentially.
ThreadSafeLogger tsLogger1 = ThreadSafeLogger.getInstance();
tsLogger1.log("Task A completed.");
ThreadSafeLogger tsLogger2 = ThreadSafeLogger.getInstance();
tsLogger2.log("Task B started.");
if (tsLogger1 == tsLogger2) {
System.out.println("Thread-safe instances are the same!");
}
}
}Singleton Use Cases
When should you consider using the Singleton pattern?
- Configuration Manager: To hold application settings, ensuring all parts of the app use the same settings.
- Logger: For a single logging service to write application events.
- Database Connection Pool: To manage a limited set of database connections efficiently across the application.
The Problem: Hardcoded Creation
Now, let's look at the Factory Method pattern. Imagine you have code that creates objects directly, like new Car() or new Truck().
What happens if you need to add a new vehicle type, or change how a Car is created? You'd have to find and update every place in your code that creates these objects. This makes your code rigid and hard to maintain!
Factory Method: Abstracting Creation
The Factory Method pattern solves this by defining an interface or abstract class for creating an object, but letting subclasses decide which class to instantiate.
- It delegates object creation to specialized 'factory' methods.
- This promotes loose coupling by allowing client code to work with interfaces instead of concrete classes.
Building with Factory Method
Let's create a system for different types of transport. We define a Transport interface, concrete transport classes, and then a TransportFactory with a factory method.
Each specific factory (e.g., CarFactory) knows how to create its specific product.
// Product Interface
interface Transport {
void deliver();
}
// Concrete Products
class Truck implements Transport {
@Override
public void deliver() {
System.out.println("Deliver by land in a truck.");
}
}
class Ship implements Transport {
@Override
public void deliver() {
System.out.println("Deliver by sea in a ship.");
}
}
// Creator Interface (with Factory Method)
abstract class Logistics {
public void planDelivery() {
Transport t = createTransport();
t.deliver();
}
// The Factory Method
public abstract Transport createTransport();
}
// Concrete Creators
class RoadLogistics extends Logistics {
@Override
public Transport createTransport() {
return new Truck();
}
}
class SeaLogistics extends Logistics {
@Override
public Transport createTransport() {
return new Ship();
}
}
public class Main {
public static void main(String[] args) {
Logistics roadLogistics = new RoadLogistics();
roadLogistics.planDelivery(); // Outputs: Deliver by land in a truck.
Logistics seaLogistics = new SeaLogistics();
seaLogistics.planDelivery(); // Outputs: Deliver by sea in a ship.
}
}Advantages of Factory Method
The Factory Method pattern brings several key benefits to your software design:
- Loose Coupling: Your client code interacts only with the
Logisticsinterface, not specificTruckorShipclasses. - Extensibility: You can easily add new transport types (e.g.,
AirLogisticswithPlane) without changing existingLogisticsor client code. - Single Responsibility: The responsibility of creating objects is moved to dedicated factory classes/methods.
Check Your Knowledge
Let's test your understanding of the Singleton and Factory Method patterns.
Recap: Singleton & Factory
Great job! In this lesson, we explored two powerful creational design patterns:
- Singleton: Ensures a class has only one instance and provides a global access point. Remember to consider thread-safety!
- Factory Method: Delegates object creation to subclasses, promoting loose coupling and making your code more extensible.
These patterns are fundamental for building flexible and maintainable software. Next, we'll dive into more creational patterns like Abstract Factory and Builder!
คำถามที่พบบ่อย
บทเรียน “Singleton และ Factory Method” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “Singleton และ Factory Method” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Clean Architecture & Design Patterns in Practice ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Clean Architecture & Design Patterns in Practice มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “Singleton และ Factory Method”
นำรูปแบบ Singleton มาใช้เพื่อสร้างอินสแตนซ์ที่ไม่ซ้ำกัน และใช้ Factory Method เพื่อสร้างออบเจ็กต์ได้อย่างยืดหยุ่น คุณปฏิบัติ Clean Architecture & Design Patterns in Practice ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Clean Architecture & Design Patterns in Practice หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Clean Architecture & Design Patterns in Practice บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “Singleton และ Factory Method” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Clean Architecture & Design Patterns in Practice นี้ได้ไหม
ได้ บทเรียน Clean Architecture & Design Patterns in Practice ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- Singleton และ Factory Method
- Abstract Factory และ Builder
- Prototype และ Object Pool
- การฉีดทรัพยากรพึ่งพาในฐานะเทคนิคการสร้าง