Hope this page could elucidate the same issue in a bit different manner.

Pattern overview

Pattern Name and Classification

A descriptive and unique name that helps in identifying and referring to the pattern.

Intent

A description of the goal behind the pattern and the reason for using it.

Also Known As

Other names for the pattern.

Motivation (Forces)

A scenario consisting of a problem and a context in which this pattern can be used.

Applicability

Situations in which this pattern is usable; the context for the pattern.

Structure

A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.

Participants

A listing of the classes and objects used in the pattern and their roles in the design.

Collaboration

A description of how classes and objects used in the pattern interact with each other.

Implementation

A description of an implementation of the pattern; the solution part of the pattern.

Consequences

A description of the results, side effects, and trade offs caused by using the pattern.

Known Uses

Examples of real usages of the pattern.

Related Patterns

Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.

Samples

For educational purposes it would be priceless to look at the working code sample. Exactly to achieve a stunning clarity it might be helpful to compose a test suite for testing the pattern features and collocate it nearby pattern source code.

Pet factory primitive

Creates some particular animal out from arbitrary number preliminarily defined pets.

Pattern code Test suite
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A pet factory abstraction
"""


class Dog(object):
    """A simple dog class"""

    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Woof!"


class Cat(object):
    """A simple cat class"""

    def __init__(self, name):
        self._name = name

    def speak(self):
        return "Meow!"


def spawn_pet(pet="dog"):
    """The factory method"""
    pets = dict(dog=Dog("Hope"),
                cat=Cat("Peace"))
    return pets[pet]

d = spawn_pet("dog")
print(d.speak())
c = spawn_pet("cat")
print(c.speak())
Woof!
Meow!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
An attempt to illustrate how pet_factory works
"""
import unittest
from pet_factory import Dog, Cat, spawn_pet


class TestPetBehavior(unittest.TestCase):

    def setUp(self):
        self.D = Dog('Hound')

    def test_dog_init_name(self):
        self.assertEqual(self.D._name, 'Hound')

    def test_dog_speak_ability(self):
        self.assertEqual(self.D.speak(), 'Woof!')

Sophisticated pet factory

Pattern code Test suite
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A pet factory abstraction
"""
from abc import ABCMeta, abstractmethod


class Animal(metaclass=ABCMeta):

    @abstractmethod
    def do_say(self):
        pass


class Dog(Animal):

    def do_say(self):
        return "Bhow Bhow!!"


class Cat(Animal):

    def do_say(self):
        return "Meow Meow!!"


class PetFactory(object):

    def make_clamor(self, object_type):
        return eval(object_type)().do_say()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Discover how it works
"""
import unittest
from sophisticated_pet_factory import Dog, \
    Cat, PetFactory


class TestPetBehavior(unittest.TestCase):

    def setUp(self):
        self.pet_factory = PetFactory()


    def test_dog_speak_ability(self):
        self.assertEqual(
            self.pet_factory.make_clamor('Dog'),
            'Bhow Bhow!!')

    def test_cat_speak_ability(self):
        self.assertEqual(
            self.pet_factory.make_clamor('Cat'),
            'Meow Meow!!')

    def tearDown(self):
        del self.pet_factory

Weapon factory

Pattern code Test suite
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
How to choose an arbitrary weapon
"""
from random import randrange


class Weapon(object):
    name = None
    cost = None

    @staticmethod
    def get_weapon(x):
        if x == 0:
            return Knife()
        if x == 1:
            return Gun()


class Knife(Weapon):
    name = 'Knife'
    cost = 20.00


class Gun(Weapon):
    name = 'Gun'
    cost = 300.00


# Create 5 random weapons
for _ in range(5):
    w = Weapon.get_weapon(randrange(2))
    print(w.name, w.cost)
Gun 300.0
Gun 300.0
Knife 20.0
Knife 20.0
Knife 20.0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
An attempt to illustrate how sample_code works
"""
import unittest

Pizza factory



blog comments powered by Disqus

Published

13 March 2017

Categories

literate programming emacs Python3

Tags