python设计模式---结构型之代理模式

时间:2022-11-14 15:10:54

主要想着nginx:)

from abc import ABCMeta, abstractmethod

# 结构型设计模式---代理模式
class Actor:
    def __init__(self):
        self.is_busy = False

    def occupied(self):
        self.is_busy = True
        print(type(self).__name__, ' is occupied with current movie.')

    def available(self):
        self.is_busy = False
        print(type(self).__name__, ' is free for the movie.')

    def get_status(self):
        return self.is_busy

class Agent:
    def __init__(self):
        self.principal = None

    def work(self):
        self.actor = Actor()

        if self.actor.get_status():
            self.actor.occupied()
        else:
            self.actor.available()

r = Agent()
r.work()

class Payment(metaclass=ABCMeta):
    @abstractmethod
    def do_pay(self):
        pass

class Bank(Payment):
    def __init__(self):
        self.card = None
        self.account = None

    def _get_account(self):
        self.account = self.card
        return self.account

    def _has_funds(self):
        print('Bank:: Checking if Account ', self._get_account(), ' has enough funds.')
        return True

    def set_card(self, card):
        self.card = card

    def do_pay(self):
        if self._has_funds():
            print('Bank:: Paying the merchant')
            return True
        else:
            print('Bank:: Sorry, not enough funds!')

class DebitCard(Payment):
    def __init__(self):
        self.bank = Bank()

    def do_pay(self):
        card = 3234324
        self.bank.set_card(card)
        return self.bank.do_pay()

class You:
    def __init__(self):
        print('You:: Let us buy the Denim shirt')
        self.debit_card = DebitCard()
        self.is_purchased = None

    def make_payment(self):
        self.is_purchased = self.debit_card.do_pay()

    def __del__(self):
        if self.is_purchased:
            print('You:: Wow! Denim shirt is Mine :-)')
        else:
            print('You:: I should earn more :(')

you = You()
you.make_payment()
Actor  is free for the movie.
You:: Let us buy the Denim shirt
Bank:: Checking   has enough funds.
Bank:: Paying the merchant
You:: Wow! Denim shirt is Mine :-)