FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-patterns/abstract_factory.py at master · cstrap/python-patterns · GitHub
cstrap
/
python-patterns
Public
forked from
faif/python-patterns
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
python-patterns
/
abstract_factory.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
64 lines (49 loc) · 1.39 KB
Breadcrumbs
python-patterns
/
abstract_factory.py
Copy path
File metadata and controls
64 lines (49 loc) · 1.39 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
"""Implementation of the abstract factory pattern"""
import
random
class
PetShop
:
"""A pet shop"""
def
__init__
(
self
,
animal_factory
=
None
):
"""pet_factory is our abstract factory.
We can set it at will."""
self
.
pet_factory
=
animal_factory
def
show_pet
(
self
):
"""Creates and shows a pet using the
abstract factory"""
pet
=
self
.
pet_factory
.
get_pet
()
print
(
"This is a lovely"
,
pet
)
print
(
"It says"
,
pet
.
speak
())
print
(
"It eats"
,
self
.
pet_factory
.
get_food
())
# Stuff that our factory makes
class
Dog
:
def
speak
(
self
):
return
"woof"
def
__str__
(
self
):
return
"Dog"
class
Cat
:
def
speak
(
self
):
return
"meow"
def
__str__
(
self
):
return
"Cat"
# Factory classes
class
DogFactory
:
def
get_pet
(
self
):
return
Dog
()
def
get_food
(
self
):
return
"dog food"
class
CatFactory
:
def
get_pet
(
self
):
return
Cat
()
def
get_food
(
self
):
return
"cat food"
# Create the proper family
def
get_factory
():
"""Let's be dynamic!"""
return
random
.
choice
([
DogFactory
,
CatFactory
])()
# Show pets with various factories
if
__name__
==
"__main__"
:
shop
=
PetShop
()
for
i
in
range
(
3
):
shop
.
pet_factory
=
get_factory
()
shop
.
show_pet
()
print
(
"="
*
20
)
Back
|
FazBrowse Home
|
New Git URL