python优雅实现适配器

读了<精通Python设计模式>,根据其中的适配器模式,我给出了一个更为优雅的实现。
#-*- coding: utf-8 -*-
# adapter pattern

class Adapter(object):
    '''Adapter class for adapter pattern
    adaptee: adapted object
    adaptedMethods: dict{known method: adapted method}'''
    def __init__(self, adaptee, adaptedMethods={}):
        self.adaptee = adaptee
        self.adaptedMethods = adaptedMethods

    @staticmethod
    def adapt(adaptee, **adaptedMethods):
        return Adapter(adaptee, adaptedMethods)

    def __getattr__(self, method):
        # method calls am of adaptee
        am = self.adaptedMethods[method]
        return getattr(self.adaptee, am)

    def __getitem__(self, method):
        # which method is adapted by 'method'
        return self.adaptedMethods[method]

    def lookup(self, method):
        # which method of adapter adapts 'method'
        for k, v in self.adaptedMethods.items():
            if v == method:
                return k


class Adaptee:
    def __init__(self, v=1):
        self.v=1

    def get(self):
        return self.v

if __name__ == '__main__':
    adaptee = Adaptee(1)
    adapter = Adapter(adaptee, {'exec':'get'})
    print(adapter.exec())
    adapter = Adapter.adapt(adaptee, exec='get')
    print(adapter.exec())
    print(adapter.lookup('get'))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值