|
1 | 1 | """
|
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 |
5 | 7 | """
|
6 |
| -from abc import abstractmethod |
| 8 | +from abc import ABC, abstractmethod |
7 | 9 |
|
8 | 10 |
|
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 |
13 | 14 |
|
| 15 | + @abstractmethod |
| 16 | + def make(self): |
| 17 | + pass |
14 | 18 |
|
15 |
| -class B: |
| 19 | + def call_edit(self): |
| 20 | + product = self.make() |
| 21 | + result = product.edit(self.file) |
| 22 | + return result |
16 | 23 |
|
17 |
| - def edit(self, file): # client |
18 |
| - return self._get_edit(file) |
19 | 24 |
|
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() |
27 | 28 |
|
28 |
| - @abstractmethod |
29 |
| - def json_edit(self, file): # product |
30 |
| - print(f"Editing Json File. . . {file.name}") |
31 | 29 |
|
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() |
35 | 52 |
|
36 | 53 |
|
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