Skip to content

Commit 80839ec

Browse files
committed
Change Factory
1 parent 2eeb09a commit 80839ec

File tree

1 file changed

+42
-28
lines changed

1 file changed

+42
-28
lines changed

src/factory2.py

Lines changed: 42 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,54 @@
11
"""
2-
Creational:
3-
Factory method
4-
3 Component => 1.Creator, 2.Product, 3.Client
2+
Factory
3+
- Factory is a creational design pattern that provides an interface for creating objects
4+
in a superclass, but allows subclasses to alter the type of objects that will be created.
5+
6+
3 component => 1. creator, 2. product, 3. client
57
"""
6-
from abc import abstractmethod
8+
from abc import ABC, abstractmethod
79

810

9-
class File:
10-
def __init__(self, name, file_format):
11-
self.name = name
12-
self.file_format = file_format
11+
class File(ABC): # creator
12+
def __init__(self, file):
13+
self.file = file
1314

15+
@abstractmethod
16+
def make(self):
17+
pass
1418

15-
class B:
19+
def call_edit(self):
20+
product = self.make()
21+
result = product.edit(self.file)
22+
return result
1623

17-
def edit(self, file): # client
18-
return self._get_edit(file)
1924

20-
def _get_edit(self, file): # creator
21-
if file.file_format == 'json': # identifier
22-
return self.json_edit(file)
23-
elif file.file_format == 'xml': # identifier
24-
return self.xml_edit(file)
25-
else:
26-
raise ValueError("So Sorry. . .")
25+
class JsonFile(File): # creator
26+
def make(self):
27+
return Json()
2728

28-
@abstractmethod
29-
def json_edit(self, file): # product
30-
print(f"Editing Json File. . . {file.name}")
3129

32-
@abstractmethod
33-
def xml_edit(self, file): # product
34-
print(f"Editing Xml File. . . {file.name}")
30+
class XmlFile(File): # creator
31+
def make(self):
32+
return Xml()
33+
34+
35+
class Json: # product
36+
def edit(self, file):
37+
return f'Working on {file} Json...'
38+
39+
40+
class Xml: # product
41+
def edit(self, file):
42+
return f'Working on {file} Xml...'
43+
44+
45+
def client(file, format): # client
46+
formats = {
47+
'json': JsonFile,
48+
'xml': XmlFile
49+
}
50+
result = formats[format](file)
51+
return result.call_edit()
3552

3653

37-
if __name__ == '__main__':
38-
first_file = File('first', 'xml')
39-
b1 = B()
40-
b1.edit(first_file)
54+
print(client('show', 'xml'))

0 commit comments

Comments
 (0)