Generic adapter class in Python

The adapter pattern is often used in programming when you need to adapt one interface to another. Here's a simple generic adapter class that can adapt just about any interface to just about any other.

class Adapter(object):
    """
    Adapts an object by replacing methods.
    Usage:
    dog = Dog()
    dog = Adapter(dog, dict(make_noise=dog.bark))
    """
    def __init__(self, obj, adapted_methods):
        """We set the adapted methods in the object's dict"""
        self.obj = obj
        self.__dict__.update(adapted_methods)
    def __getattr__(self, attr):
        """All non-adapted calls are passed to the object"""
        return getattr(self.obj, attr)


This adapter can be used to adapt many objects with different interfaces into a single, unified interface.


import os
class Dog(object):
    def __init__(self):
        self.name = "Dog"
    def bark(self):
        return "woof!"

class Cat(object):
    def __init__(self):
        self.name = "Cat"
    def meow(self):
        return "meow!"

class Human(object):
    def __init__(self):
        self.name = "Human"
    def speak(self):
        return "'hello'"

class Car(object):
    def __init__(self):
        self.name = "Car"
    def make_noise(self, octane_level):
        return "vroom%s" % ("!" * octane_level)

class Adapter(object):
    """
    Adapts an object by replacing methods.
    Usage:
    dog = Dog
    dog = Adapter(dog, dict(make_noise=dog.bark))
    """
    def __init__(self, obj, adapted_methods):
        """We set the adapted methods in the object's dict"""
        self.obj = obj
        self.__dict__.update(adapted_methods)
    def __getattr__(self, attr):
        """All non-adapted calls are passed to the object"""
        return getattr(self.obj, attr)

def main():
    objects = []
    dog = Dog()
    objects.append(Adapter(dog, dict(make_noise=dog.bark)))
    cat = Cat()
    objects.append(Adapter(cat, dict(make_noise=cat.meow)))
    human = Human()
    objects.append(Adapter(human, dict(make_noise=human.speak)))
    car = Car()
    car_noise = lambda : car.make_noise(3)
    objects.append(Adapter(car, dict(make_noise=car_noise)))

    for obj in objects:
        print "A", obj.name, "goes", obj.make_noise()

if __name__ == "__main__":
    main()


Output:

A Dog goes woof!
A Cat goes meow!
A Human goes 'hello'
A Car goes vroom!!!


python 适配器模式 更详细具体的描述:

http://ginstrom.com/scribbles/2009/03/27/the-adapter-pattern-in-python/

你可能感兴趣的:(python,Adapter,Adapter,适配器)