8

これは、ストラテジー デザイン パターンでの私の最初の試みです。

私は Python を使用した建築経験がないので、建設的なコメントを歓迎します。

これを Stack-Over-Flow に投稿するのは、今朝の健全性チェックとして役立つと思ったからです。明らかに、私はこのスレッド (恐ろしい検証フレーズ) に十分なコンテキストを提供していないと思われるため、ダックのようにクワックする必要があります。

クワ、クワ、クワ :-)

#!/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!

"""
4

0 に答える 0