Factory Pattern menyediakan interface untuk membuat object tanpa menentukan class spesifik yang akan dibuat. Keputusan "object mana yang dibuat" ditangani oleh factory.
Analogi: Kamu pesan kopi di kafe. Kamu bilang "cappuccino" — barista yang tahu cara membuatnya. Kamu tidak perlu tahu detail prosesnya.
Masalah yang diselesaikan:
- Logika pembuatan object yang kompleks tersebar di banyak tempat
- Kode penuh
if/elseatauswitchuntuk menentukan tipe object - Sulit menambah tipe baru tanpa mengubah banyak kode
Simple Factory:
function createNotification(type, message) {
switch (type) {
case "email":
return {
type: "email",
message,
send() { console.log(`Email: ${this.message}`); }
};
case "sms":
return {
type: "sms",
message: message.slice(0, 160), // SMS limit
send() { console.log(`SMS: ${this.message}`); }
};
case "push":
return {
type: "push",
message,
send() { console.log(`Push: ${this.message}`); }
};
default:
throw new Error(`Unknown type: ${type}`);
}
}
const notif = createNotification("email", "Pesanan dikonfirmasi");
notif.send(); // "Email: Pesanan dikonfirmasi"
Factory dengan Registry (lebih extensible):
class NotificationFactory {
constructor() {
this.creators = {};
}
register(type, creator) {
this.creators[type] = creator;
}
create(type, message) {
const creator = this.creators[type];
if (!creator) throw new Error(`Unknown type: ${type}`);
return creator(message);
}
}
const factory = new NotificationFactory();
factory.register("email", (msg) => ({
send() { console.log(`Email: ${msg}`); }
}));
factory.register("whatsapp", (msg) => ({
send() { console.log(`WA: ${msg}`); }
}));
// Mudah menambah tipe baru tanpa mengubah factory!
factory.register("telegram", (msg) => ({
send() { console.log(`Telegram: ${msg}`); }
}));
const wa = factory.create("whatsapp", "Halo!");
wa.send(); // "WA: Halo!"
Factory di dunia nyata:
// React.createElement — factory untuk React elements
React.createElement("div", { className: "box" }, "Hello");
React.createElement(MyComponent, { data: items });
// document.createElement — factory untuk DOM elements
const div = document.createElement("div");
const canvas = document.createElement("canvas");
// jQuery — $() adalah factory
const $div = $("<div>").addClass("box");
Abstract Factory — factory yang membuat family of objects:
function createUIKit(theme) {
if (theme === "dark") {
return {
createButton: (text) => ({ text, bg: "#333", color: "#fff" }),
createInput: (placeholder) => ({ placeholder, bg: "#222", border: "#555" })
};
}
return {
createButton: (text) => ({ text, bg: "#fff", color: "#333" }),
createInput: (placeholder) => ({ placeholder, bg: "#fff", border: "#ccc" })
};
}
const ui = createUIKit("dark");
const btn = ui.createButton("Submit");
// { text: "Submit", bg: "#333", color: "#fff" }
Kapan pakai Factory Pattern:
- Saat pembuatan object melibatkan logika kompleks
- Saat tipe object ditentukan saat runtime
- Saat ingin centralize object creation untuk konsistensi