Skip to content

Commit df77f2a

Browse files
committed
add implementation of abstract factory
1 parent 0695592 commit df77f2a

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

creational/abstract_factory.py

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
55

66
"""Implementation of the abstract factory pattern"""
7-
7+
import six
8+
import abc
89
import random
910

1011

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

7475

76+
# Implementation 2 of an abstract factory
77+
@six.add_metaclass(abc.ABCMeta)
78+
class Pet(object):
79+
80+
@classmethod
81+
def from_name(cls, name):
82+
for sub_cls in cls.__subclasses__():
83+
if name == sub_cls.__name__.lower():
84+
return sub_cls()
85+
86+
@abc.abstractmethod
87+
def speak(self):
88+
""""""
89+
90+
91+
class Kitty(Pet):
92+
def speak(self):
93+
return "Miao"
94+
95+
96+
class Duck(Pet):
97+
def speak(self):
98+
return "Quak"
99+
100+
75101
# Show pets with various factories
76102
if __name__ == "__main__":
77103
for i in range(3):
78104
shop = PetShop(get_factory())
79105
shop.show_pet()
80106
print("=" * 20)
81107

108+
for name0 in ["kitty", "duck"]:
109+
pet = Pet.from_name(name0)
110+
print("{}: {}".format(name0, pet.speak()))
111+
82112
### OUTPUT ###
83-
# We have a lovely Dog
84-
# It says woof
85-
# We also have dog food
113+
# We have a lovely Cat
114+
# It says meow
115+
# We also have cat food
86116
# ====================
87117
# We have a lovely Dog
88118
# It says woof
@@ -92,3 +122,5 @@ def get_factory():
92122
# It says meow
93123
# We also have cat food
94124
# ====================
125+
# kitty: Miao
126+
# duck: Quak

tests/test_abstract_factory.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# -*- coding: utf-8 -*-
33
import unittest
44
from creational.abstract_factory import PetShop,\
5-
Dog, Cat, DogFactory, CatFactory
5+
Dog, Cat, DogFactory, CatFactory, Pet
66
try:
77
from unittest.mock import patch
88
except ImportError:
@@ -54,3 +54,12 @@ def test_dog_shall_woof(cls):
5454

5555
def test_dog_shall_be_printable(cls):
5656
cls.assertEqual(str(cls.d), 'Dog')
57+
58+
59+
class PetTest(unittest.TestCase):
60+
61+
def test_from_name(self):
62+
test_cases = [("kitty", "Miao"), ("duck", "Quak")]
63+
for name, expected_speech in test_cases:
64+
pet = Pet.from_name(name)
65+
self.assertEqual(pet.speak(), expected_speech)

0 commit comments

Comments
 (0)