Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ cache:
- pip

install:
- travis_retry pip install -q coveralls codecov
- travis_retry pip install -q coveralls codecov six
- pip install flake8 # eventually worth

script:
Expand Down
40 changes: 36 additions & 4 deletions creational/abstract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/

"""Implementation of the abstract factory pattern"""

import six
import abc
import random


Expand Down Expand Up @@ -72,17 +73,46 @@ def get_factory():
return random.choice([DogFactory, CatFactory])()


# Implementation 2 of an abstract factory
@six.add_metaclass(abc.ABCMeta)
class Pet(object):

@classmethod
def from_name(cls, name):
for sub_cls in cls.__subclasses__():
if name == sub_cls.__name__.lower():
return sub_cls()

@abc.abstractmethod
def speak(self):
""""""


class Kitty(Pet):
def speak(self):
return "Miao"


class Duck(Pet):
def speak(self):
return "Quak"


# Show pets with various factories
if __name__ == "__main__":
for i in range(3):
shop = PetShop(get_factory())
shop.show_pet()
print("=" * 20)

for name0 in ["kitty", "duck"]:
pet = Pet.from_name(name0)
print("{}: {}".format(name0, pet.speak()))

### OUTPUT ###
# We have a lovely Dog
# It says woof
# We also have dog food
# We have a lovely Cat
# It says meow
# We also have cat food
# ====================
# We have a lovely Dog
# It says woof
Expand All @@ -92,3 +122,5 @@ def get_factory():
# It says meow
# We also have cat food
# ====================
# kitty: Miao
# duck: Quak
11 changes: 10 additions & 1 deletion tests/test_abstract_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
import unittest
from creational.abstract_factory import PetShop,\
Dog, Cat, DogFactory, CatFactory
Dog, Cat, DogFactory, CatFactory, Pet
try:
from unittest.mock import patch
except ImportError:
Expand Down Expand Up @@ -54,3 +54,12 @@ def test_dog_shall_woof(cls):

def test_dog_shall_be_printable(cls):
cls.assertEqual(str(cls.d), 'Dog')


class PetTest(unittest.TestCase):

def test_from_name(self):
test_cases = [("kitty", "Miao"), ("duck", "Quak")]
for name, expected_speech in test_cases:
pet = Pet.from_name(name)
self.assertEqual(pet.speak(), expected_speech)