10 Pola Desain Pemrograman yang Harus Diketahui oleh Developer

10 Pola Desain Pemrograman yang Harus Diketahui

Pendahuluan

Pola desain pemrograman (design patterns) adalah solusi yang sudah terbukti untuk masalah umum dalam pengembangan perangkat lunak. Pola-pola ini membantu developer membuat kode yang lebih terstruktur, mudah dipelihara, dan fleksibel untuk perubahan di masa depan. Artikel ini akan membahas 10 pola desain pemrograman yang harus Anda ketahui.


1. Singleton

Deskripsi: Memastikan bahwa hanya ada satu instance dari suatu kelas di seluruh aplikasi.

Kode Contoh (Python):

python

class Singleton: _instance = None @staticmethod def get_instance(): if Singleton._instance is None: Singleton._instance = Singleton() return Singleton._instance

2. Factory

Deskripsi: Menyediakan cara untuk membuat objek tanpa menentukan kelas objek secara eksplisit.

Kode Contoh (Python):

python

class Shape: def draw(self): pass class Circle(Shape): def draw(self): return "Drawing a Circle" class Square(Shape): def draw(self): return "Drawing a Square" class ShapeFactory: @staticmethod def get_shape(shape_type): if shape_type == "Circle": return Circle() elif shape_type == "Square": return Square() return None shape = ShapeFactory.get_shape("Circle") print(shape.draw())

3. Observer

Deskripsi: Mengamati perubahan pada suatu objek dan memberi tahu objek lain yang terkait.

Kode Contoh (Python):

python

class Subject: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def notify_observers(self, message): for observer in self._observers: observer.update(message) class Observer: def update(self, message): print("Observer received:", message) subject = Subject() observer1 = Observer() observer2 = Observer() subject.add_observer(observer1) subject.add_observer(observer2) subject.notify_observers("State has changed!")

4. Strategy

Deskripsi: Mengganti algoritma atau perilaku objek secara dinamis.

Kode Contoh (Python):

python

class PaymentStrategy: def pay(self, amount): pass class CreditCardPayment(PaymentStrategy): def pay(self, amount): print(f"Paid {amount} using Credit Card.") class PayPalPayment(PaymentStrategy): def pay(self, amount): print(f"Paid {amount} using PayPal.") class PaymentContext: def __init__(self, strategy): self._strategy = strategy def execute_payment(self, amount): self._strategy.pay(amount) context = PaymentContext(CreditCardPayment()) context.execute_payment(100)

5. Decorator

Deskripsi: Menambahkan fungsionalitas baru ke suatu objek tanpa mengubah struktur dasarnya.

Kode Contoh (Python):

python

def bold(func): def wrapper(): return f"<b>{func()}</b>" return wrapper @bold def say_hello(): return "Hello, World!" print(say_hello())

6. Adapter

Deskripsi: Memungkinkan dua antarmuka yang tidak kompatibel bekerja bersama.

Kode Contoh (Python):

python

class OldSystem: def old_method(self): return "Old system method" class Adapter: def __init__(self, old_system): self.old_system = old_system def new_method(self): return self.old_system.old_method() adapter = Adapter(OldSystem()) print(adapter.new_method())

7. Command

Deskripsi: Mengenkapsulasi permintaan sebagai objek, sehingga memungkinkan undo atau pengaturan ulang tindakan.

Kode Contoh (Python):

python

class Command: def execute(self): pass class LightOnCommand(Command): def __init__(self, light): self.light = light def execute(self): self.light.turn_on() class LightOffCommand(Command): def __init__(self, light): self.light = light def execute(self): self.light.turn_off() class Light: def turn_on(self): print("Light is ON") def turn_off(self): print("Light is OFF") class RemoteControl: def __init__(self): self.command = None def set_command(self, command): self.command = command def press_button(self): if self.command: self.command.execute() light = Light() remote = RemoteControl() remote.set_command(LightOnCommand(light)) remote.press_button() remote.set_command(LightOffCommand(light)) remote.press_button()

8. Prototype

Deskripsi: Membuat objek baru dengan menduplikasi objek yang sudah ada.

Kode Contoh (Python):

python

import copy class Prototype: def __init__(self, name, attributes): self.name = name self.attributes = attributes def clone(self): return copy.deepcopy(self) original = Prototype("Original", {"key1": "value1", "key2": "value2"}) clone = original.clone() print("Original:", original.name, original.attributes) print("Clone:", clone.name, clone.attributes)

9. Composite

Deskripsi: Menyusun objek ke dalam struktur pohon untuk mewakili hierarki bagian.

Kode Contoh (Python):

python

class Component: def operation(self): pass class Leaf(Component): def __init__(self, name): self.name = name def operation(self): return f"Leaf {self.name}" class Composite(Component): def __init__(self, name): self.name = name self.children = [] def add(self, component): self.children.append(component) def remove(self, component): self.children.remove(component) def operation(self): results = [child.operation() for child in self.children] return f"Composite {self.name}: [{' | '.join(results)}]" leaf1 = Leaf("A") leaf2 = Leaf("B") composite = Composite("Root") composite.add(leaf1) composite.add(leaf2) print(composite.operation())

10. Template Method

Deskripsi: Mendefinisikan kerangka algoritma, dengan beberapa langkah diatur oleh subclass.

Kode Contoh (Python):

python

from abc import ABC, abstractmethod class Template(ABC): def template_method(self): self.step1() self.step2() self.hook() self.step3() def step1(self): print("Step 1: Common behavior") @abstractmethod def step2(self): pass def hook(self): pass def step3(self): print("Step 3: Common behavior") class ConcreteClass(Template): def step2(self): print("Step 2: Custom behavior") def hook(self): print("Hook: Optional additional behavior") obj = ConcreteClass() obj.template_method()

Kesimpulan

Pola desain pemrograman adalah alat penting untuk meningkatkan kualitas kode Anda. Dengan memahami dan menerapkannya, Anda dapat menciptakan solusi yang lebih efisien, dapat diandalkan, dan mudah dikembangkan di masa depan.

Lebih baru Lebih lama