ภาพรวม (Overview)
Design Patterns คือ "สูตรอาหาร" ที่เชฟระดับโลกคิดมาแล้วว่าแก้ปัญหาซ้ำซากได้ดีที่สุด ไม่ต้องท่องจำทั้ง 23 แบบ (GoF) เอาแค่ที่ได้ใช้จริงใน Web Development ก็พอครับ
1. Singleton Pattern: มีแค่หนึ่งเดียว
ใช้กับสิ่งที่ควรมีแค่อันเดียวทั้งระบบ เช่น DatabaseConnection, Logger, Config
ป้องกันการ new Database connection ใหม่พร่ำเพรื่อจน Server พัง
class Database {
private static instance: Database;
private constructor() {
/* connect db */
}
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
// ใช้กี่ครั้งก็ได้ Database ตัวเดิม
const db1 = Database.getInstance();
const db2 = Database.getInstance(); // db1 === db2
2. Factory Pattern: โรงงานผลิต Object
ใช้เมื่อเรามี Object หลายประเภทที่มี Interface เหมือนกัน แต่ไม่อยากให้โค้ดส่วนอื่นรู้ Logic การสร้าง
interface PaymentProcessor {
pay(amount: number): void;
}
class Stripe implements PaymentProcessor { ... }
class PayPal implements PaymentProcessor { ... }
class PaymentFactory {
static create(type: 'stripe' | 'paypal'): PaymentProcessor {
if (type === 'stripe') return new Stripe();
if (type === 'paypal') return new PayPal();
throw new Error('Unknown payment method');
}
}
// คนเรียกใช้ไม่ต้องรู้ว่าข้างในสร้างยังไง แค่ขอมาก็พอ
const payment = PaymentFactory.create('stripe');
payment.pay(100);
3. Observer Pattern: กระจายข่าว
หัวใจของ Event-Driven Architecture, Redux, RxJS เมื่อ "ตัวแม่" (Subject) เปลี่ยนแปลง -> แจ้งเตือน "ตัวลูก" (Observers) ทุกตัวทันที
class NewsAgency {
// Subject
private subscribers: Function[] = [];
subscribe(fn: Function) {
this.subscribers.push(fn);
}
notify(news: string) {
this.subscribers.forEach((sub) => sub(news));
}
}
const cnn = new NewsAgency();
cnn.subscribe((news) => console.log("Reader 1 got:", news));
cnn.subscribe((news) => console.log("Reader 2 got:", news));
cnn.notify("Breaking News!"); // Reader 1 & 2 เด้งพร้อมกัน
สรุป
Pattern มีไว้แก้ปัญหา ไม่ใช่มีไว้โชว์เท่
- ใช้ Singleton เพื่อคุม Resource
- ใช้ Factory เพื่อลด Coupling การสร้าง Object
- ใช้ Observer เพื่อทำระบบ Event/Real-time
รู้วิธีใช้ แล้วโค้ดจะยืดหยุ่นดูแลรักษาง่ายครับ!