SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы
НазадМетки: python
This is the function object in its purest sense: a method that’s an object. By wrapping a method in an object, you can pass it to other methods or objects as a parameter, to tell them to perform this particular operation in the process of fulfilling your request:
# FunctionObjects/CommandPattern.py
class Command:
    def execute(self): pass
class Loony(Command):
    def execute(self):
        print("You're a loony.")
class NewBrain(Command):
    def execute(self):
        print("You might even need a new brain.")
class Afford(Command):
    def execute(self):
        print("I couldn't afford a whole new brain.")
# An object that holds commands:
class Macro:
    def __init__(self):
        self.commands = []
    def add(self, command):
        self.commands.append(command)
    def run(self):
        for c in self.commands:
            c.execute()
macro = Macro()
macro.add(Loony())
macro.add(NewBrain())
macro.add(Afford())
macro.run()
The primary point of Command is to allow you to hand a desired action to a method or object. In the above example, this provides a way to queue a set of actions to be performed collectively. In this case, it allows you to dynamically create new behavior, something you can normally only do by writing new code but in the above example could be done by interpreting a script (see the Interpreter pattern if what you need to do gets very complex).
Design Patterns says that “Commands are an object-oriented replacement for callbacks.” However, I think that the word “back” is an essential part of the concept of callbacks. That is, I think a callback actually reaches back to the creator of the callback. On the other hand, with a Command object you typically just create it and hand it to some method or object, and are not otherwise connected over time to the Command object. That’s my take on it, anyway. Later in this book, I combine a group of design patterns under the heading of “callbacks.”