forked from amirbigg/python-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfactory.py
More file actions
54 lines (37 loc) · 980 Bytes
/
factory.py
File metadata and controls
54 lines (37 loc) · 980 Bytes
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
"""
Factory
- Factory is a creational design pattern that provides an interface for creating objects
in a superclass, but allows subclasses to alter the type of objects that will be created.
3 component => 1. creator, 2. product, 3. client
"""
from abc import ABC, abstractmethod
class File(ABC): # creator
def __init__(self, file):
self.file = file
@abstractmethod
def make(self):
pass
def call_edit(self):
product = self.make()
result = product.edit(self.file)
return result
class JsonFile(File): # creator
def make(self):
return Json()
class XmlFile(File): # creator
def make(self):
return Xml()
class Json: # product
def edit(self, file):
return f'Working on {file} Json...'
class Xml: # product
def edit(self, file):
return f'Working on {file} Xml...'
def client(file, format): # client
formats = {
'json': JsonFile,
'xml': XmlFile
}
result = formats[format](file)
return result.call_edit()
print(client('show', 'xml'))