大話設計モードのPython実現【戦略モード】


# coding=utf8

__author__ = 'smilezjw'


class CashSuper(object):
    def accept_cash(self, money):
        pass


class CashNormal(CashSuper):
    def accept_cash(self, money):
        return money


class CashRebate(CashSuper):
    discount = 1
    def __init__(self, discount):
        self.discount = discount

    def accept_cash(self, money):
        return money * self.discount


class CashReturn(CashSuper):
    total = 0
    ret = 0
    def __init__(self, total, ret):
        self.total = total
        self.ret = ret

    def accept_cash(self, money):
        if money > self.total:
            return money - self.ret
        return money


class CashContext(object):
    cs = None
    def __init__(self, type):
        if type == 1:
            cs0 = CashNormal()
            self.cs = cs0
        elif type == 2:
            cs1 = CashReturn(300, 100)
            self.cs = cs1
        elif type == 3:
            cs2 = CashRebate(0.8)
            self.cs = cs2

    def get_result(self, money):
        return self.cs.accept_cash(money)

if __name__ == '__main__':
    money = input('Total momey: ')
    type = input('1- , 2- 300 100, 3- 8 : ')
    context = CashContext(type)
    print context.get_result(money)

戦略モデルと単純な工場モデルを組み合わせた.
モードの特徴:ポリシーモードはクライアントが1つのクラスCashContextを認識するだけでよいが、単純なファクトリモードを採用するには2つのクラスCashSuperとCashFactoryを認識する必要がある.ポリシーモードは結合度を低下させる.