banner
Jun 5, 2023
95 Views

Bridge Pattern

Written by
banner

Decouple an abstraction from its implementation so that the two can vary independently.

Tách rời trừu tượng khỏi cách viết code của nó để hai phần này có thể thay đổi một cách độc lập.

Ví dụ:

Bạn có 2 loại cá, 1 con ăn chay và 1 con ăn giun. Lúc này chúng ta tách thành 2 lớp trừu tượng là:

  • Cá (fish): VeganFish, NonVeganFish.
  • Đồ ăn (food): VeganFood, NonVeganFood.
from abc import ABC, abstractmethod

# Abstraction interface
class Fish(ABC):
    def __init__(self, food):
        self.food= food

    @abstractmethod
    def eat(self):
        pass

# Concrete implementation interface
class Food(ABC):
    @abstractmethod
    def feed(self):
        pass

# Concrete implementation classes
class VeganFood(Food):
    def feed(self):
        return "vegan food"

class NonVeganFood(Food):
    def feed(self):
        return "non vegan food"

# Refined Abstraction classes
class VeganFish(Fish):
    def eat(self):
        return f"Vegan fish was fed using {self.food.feed()}"

class NonVeganFish(Fish):
    def eat(self):
        return f"Non vegan fish was fed using {self.food.feed()}"

# Usage example
fish_1= VeganFish(VeganFood())
print(fish_1.eat())  # Output: Vegan fish was fed using vegan food

fish_2= NonVeganFish(NonVeganFood())
print(fish_2.eat())  # Output: Non vegan fish was fed using non vegan food

Article Categories:
Uncategorized
banner

Leave a Reply

Your email address will not be published. Required fields are marked *