Skip to content

Commit 48ee39a

Browse files
Prototype Patterns
1 parent 12c39e3 commit 48ee39a

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import copy
2+
3+
4+
class Address:
5+
def __init__(self, street_address, city, country):
6+
self.country = country
7+
self.city = city
8+
self.street_address = street_address
9+
10+
def __str__(self):
11+
return f'{self.street_address}, {self.city}, {self.country}'
12+
13+
14+
class Person:
15+
def __init__(self, name, address):
16+
self.name = name
17+
self.address = address
18+
19+
def __str__(self):
20+
return f'{self.name} lives at {self.address}'
21+
22+
23+
john = Person("John", Address("123 London Road", "London", "UK"))
24+
print(john)
25+
# jane = john
26+
jane = copy.deepcopy(john)
27+
jane.name = "Jane"
28+
jane.address.street_address = "124 London Road"
29+
print(john, jane)
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import copy
2+
3+
4+
class Address:
5+
def __init__(self, street_address, suite, city):
6+
self.suite = suite
7+
self.city = city
8+
self.street_address = street_address
9+
10+
def __str__(self):
11+
return f'{self.street_address}, Suite #{self.suite}, {self.city}'
12+
13+
class Employee:
14+
def __init__(self, name, address):
15+
self.address = address
16+
self.name = name
17+
18+
def __str__(self):
19+
return f'{self.name} works at {self.address}'
20+
21+
22+
class EmployeeFactory:
23+
main_office_employee = Employee("", Address("123 East Dr", 0, "London"))
24+
aux_office_employee = Employee("", Address("123B East Dr", 0, "London"))
25+
26+
@staticmethod
27+
def __new_employee(proto, name, suite):
28+
result = copy.deepcopy(proto)
29+
result.name = name
30+
result.address.suite = suite
31+
return result
32+
33+
@staticmethod
34+
def new_main_office_employee(name, suite):
35+
return EmployeeFactory.__new_employee(
36+
EmployeeFactory.main_office_employee,
37+
name, suite
38+
)
39+
40+
@staticmethod
41+
def new_aux_office_employee(name, suite):
42+
return EmployeeFactory.__new_employee(
43+
EmployeeFactory.aux_office_employee,
44+
name, suite
45+
)
46+
47+
# main_office_employee = Employee("", Address("123 East Dr", 0, "London"))
48+
# aux_office_employee = Employee("", Address("123B East Dr", 0, "London"))
49+
50+
# john = copy.deepcopy(main_office_employee)
51+
#john.name = "John"
52+
#john.address.suite = 101
53+
#print(john)
54+
55+
# would prefer to write just one line of code
56+
jane = EmployeeFactory.new_aux_office_employee("Jane", 200)
57+
print(jane)
58+

0 commit comments

Comments
 (0)