这是我第一次尝试策略设计模式。
我没有使用Python的架构经验,所以欢迎提出建设性意见。
我将此发布到Stack-Over-Flow,因为我觉得今天早上它可以作为一个健全性检查。显然,据说我没有为这个线程提供足够的上下文(可怕的验证短语)所以我将不得不像鸭子那样使用Quack。
嘎嘎,嘎嘎,嘎嘎: - )
#!/usr/bin/env python
"""
Head First Design Patterns - Strategy Pattern
My attempt to implement the Strategy Pattern, described in Chapter 1.
Sanity Warning: I am currently learning Python, so please don't expect the
exquisite design, planning, construction, and execution of the Curiosity mission.
Expect Ducks... Quacking...
Design Principle: "Favour composition over inheritance"
To the Pythonista community: What is the most elegant, readable, and simplest way
of implementing the HFDP Strategy Pattern?
"""
import abc
"""
Abstract Base Classes
Duck > QuackBehaviour > FlyBehaviour
"""
class Duck(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self.quackBehaviour = None;
self.flyBehaviour = None;
@abc.abstractmethod
def display(self):
pass
def performQuack(self):
self.quackBehaviour.quack()
def performFly(self):
self.flyBehaviour.fly()
def swim(self):
print "All ducks float, even decoys!"
class QuackBehaviour(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def quack(self):
"""All sub classes agree to quack"""
pass
class FlyBehaviour(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def fly(self):
"""All sub classes agree to fly"""
pass
"""
Sub class implementations
MallardDuck > Quack > MuteQuack > SqueakQuack > FlyWithWings > FlyNoWay > FlyRocketPowered
"""
class MallardDuck(Duck):
def __init__(self):
Duck.quackBehaviour = Quack()
Duck.flyBehaviour = FlyWithWings()
def display(self):
print "I'm a real Mallard Duck"
class Quack(QuackBehaviour):
def quack(self):
print "Quack"
class MuteQuack(QuackBehaviour):
def quack(self):
print "<< Silence >>"
class SqueakQuack(QuackBehaviour):
def quack(self):
print "Squeak"
class FlyWithWings(FlyBehaviour):
def fly(self):
print "I'm flying!!"
class FlyNoWay(FlyBehaviour):
def fly(self):
print "I can't fly"
class FlyRocketPowered(FlyBehaviour):
def fly(self):
print "I'm flying with a rocket!"
"""
Cue Space Odyssey Opening...
"""
if __name__ == '__main__':
mallard = MallardDuck()
mallard.display()
mallard.performQuack()
mallard.performFly()
mallard.flyBehaviour = FlyRocketPowered()
mallard.performFly()
"""
Output:
I'm a real Mallard Duck
Quack
I'm flying!!
I'm flying with a rocket!
"""