Skip to content

Commit 65e93db

Browse files
committed
Improve design patterns code
1 parent 0ce3928 commit 65e93db

File tree

18 files changed

+200
-131
lines changed

18 files changed

+200
-131
lines changed

design_patterns/command/code.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,38 @@
11
from abc import ABCMeta
22

3+
34
class Command(metaclass=ABCMeta):
4-
def __init__(self,recv):
5-
self.recv=recv
5+
def __init__(self, recv):
6+
self.recv = recv
67

78
def execute(self):
89
pass
910

11+
1012
class ConcreteCommand(Command):
11-
def __init__(self,recv):
12-
self.recv=recv
13+
def __init__(self, recv):
14+
self.recv = recv
1315

1416
def execute(self):
1517
self.recv.action()
1618

19+
1720
class Receiver:
1821
def action(self):
1922
print("Receiver Action")
2023

24+
2125
class Invoker:
22-
def command(self,cmd):
23-
self.cmd=cmd
24-
26+
def command(self, cmd):
27+
self.cmd = cmd
28+
2529
def execute(self):
2630
self.cmd.execute()
2731

32+
2833
if __name__ == "__main__":
29-
recv=Receiver()
30-
cmd=ConcreteCommand(recv)
31-
invoker=Invoker()
34+
recv = Receiver()
35+
cmd = ConcreteCommand(recv)
36+
invoker = Invoker()
3237
invoker.command(cmd)
33-
invoker.execute()
38+
invoker.execute()

design_patterns/command/real.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,52 @@
11
from abc import ABCMeta, abstractmethod
22

3+
34
class Order(metaclass=ABCMeta):
45
@abstractmethod
56
def execute(self):
67
pass
78

9+
810
class BuyStockOrder(Order):
9-
def __init__(self,stock):
10-
self.stock=stock
11-
11+
def __init__(self, stock):
12+
self.stock = stock
13+
1214
def execute(self):
1315
self.stock.buy()
1416

17+
1518
class SellStockOrder(Order):
16-
def __init__(self,stock):
17-
self.stock=stock
18-
19+
def __init__(self, stock):
20+
self.stock = stock
21+
1922
def execute(self):
2023
self.stock.sell()
2124

25+
2226
class StockTrade:
2327
def buy(self):
2428
print("You will buy stocks")
2529

2630
def sell(self):
2731
print("You will sell stocks")
2832

33+
2934
class Agent:
3035
def __init__(self):
31-
self.__orderQueue=[]
36+
self.__orderQueue = []
3237

33-
def placeOrder(self,order):
38+
def placeOrder(self, order):
3439
self.__orderQueue.append(order)
3540
order.execute()
3641

3742

38-
if __name__=="__main__":
39-
#Cliente
40-
stock=StockTrade()
41-
buyStock=BuyStockOrder(stock)
42-
sellStock=SellStockOrder(stock)
43+
if __name__ == "__main__":
44+
# Client
45+
stock = StockTrade()
46+
buyStock = BuyStockOrder(stock)
47+
sellStock = SellStockOrder(stock)
4348

44-
#Chamador
45-
agent=Agent()
49+
# Agent
50+
agent = Agent()
4651
agent.placeOrder(buyStock)
47-
agent.placeOrder(sellStock)
52+
agent.placeOrder(sellStock)

design_patterns/command/wizard.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
class Wizard():
2-
def __init__(self,src,rootdir):
3-
self.choices=[]
4-
self.rootdir=rootdir
5-
self.src=src
2+
def __init__(self, src, rootdir):
3+
self.choices = []
4+
self.rootdir = rootdir
5+
self.src = src
66

7-
def preferences(self,command):
7+
def preferences(self, command):
88
self.choices.append(command)
99

1010
def execute(self):
1111
for choice in self.choices:
1212
if list(choice.values())[0]:
13-
print("Copying binaries --",self.src,"to ",self.rootdir)
13+
print(f"Copying binaries -- {self.src} to {self.rootdir}")
1414
else:
1515
print("No Operation")
1616

17+
1718
if __name__ == '__main__':
18-
##Código do cliente
19-
wizard = Wizard('python3.8.zip','/usr/bin')
20-
##Os usuários escolhem instalar somente Python
21-
wizard.preferences({'python':True})
22-
wizard.preferences({'java':False})
23-
wizard.execute()
19+
# Client code
20+
wizard = Wizard('python3.8.zip', '/usr/bin')
21+
22+
# Users prefer to install only Python
23+
wizard.preferences({'python': True})
24+
wizard.preferences({'java': False})
25+
wizard.execute()

design_patterns/facade/code.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,5 +65,6 @@ def __del__(self):
6565
print("You:: Thanks to Event Manager, all preparations done! Phew!")
6666

6767

68-
you = You()
69-
you.askEventManager()
68+
if __name__ == "__main__":
69+
you = You()
70+
you.askEventManager()
Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,24 @@
11
from abc import ABCMeta, abstractmethod
22

3+
34
class PizzaFactory(metaclass=ABCMeta):
45
@abstractmethod
56
def createVegPizza(self):
67
pass
7-
8+
89
@abstractmethod
910
def createNonVegPizza(self):
1011
pass
1112

13+
1214
class IndianPizzaFactory(PizzaFactory):
1315
def createVegPizza(self):
1416
return DeluxVeggiePizza()
1517

1618
def createNonVegPizza(self):
1719
return ChickenPizza()
1820

21+
1922
class USPizzaFactory(PizzaFactory):
2023
def createVegPizza(self):
2124
return MexicanVegPizza()
@@ -24,35 +27,38 @@ def createNonVegPizza(self):
2427
return HamPizza()
2528

2629

27-
2830
class VegPizza(metaclass=ABCMeta):
2931
@abstractmethod
3032
def prepare(self, VegPizza):
3133
pass
3234

35+
3336
class NonVegPizza(metaclass=ABCMeta):
3437
@abstractmethod
3538
def serve(self, VegPizza):
3639
pass
3740

41+
3842
class DeluxVeggiePizza(VegPizza):
3943
def prepare(self):
4044
print("Prepare", type(self).__name__)
4145

46+
4247
class ChickenPizza(NonVegPizza):
4348
def serve(self, VegPizza):
44-
print(type(self).__name__," is served with Chicken on ", type(VegPizza).__name__)
49+
print(type(self).__name__, " is served with Chicken on ", type(VegPizza).__name__)
50+
4551

4652
class MexicanVegPizza(VegPizza):
4753
def prepare(self):
4854
print("Prepare", type(self).__name__)
4955

56+
5057
class HamPizza(NonVegPizza):
51-
def serve(self,VegPizza):
58+
def serve(self, VegPizza):
5259
print(type(self).__name__, " is served with Ham on ", type(VegPizza).__name__)
5360

5461

55-
5662
class PizzaStore:
5763
def __init__(self):
5864
pass
@@ -65,5 +71,7 @@ def makePizza(self):
6571
self.VegPizza.prepare()
6672
self.NonVegPizza.serve(self.VegPizza)
6773

68-
pizza = PizzaStore()
69-
pizza.makePizza()
74+
75+
if __name__ == "__main__":
76+
pizza = PizzaStore()
77+
pizza.makePizza()

design_patterns/factory/factory_method.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,35 @@
11
from abc import ABCMeta, abstractmethod
22

3+
34
class Section(metaclass=ABCMeta):
45
@abstractmethod
56
def describe(self):
67
pass
78

9+
810
class PersonalSection(Section):
911
def describe(self):
1012
print("Personal Section")
1113

14+
1215
class AlbumSection(Section):
1316
def describe(self):
1417
print("Album Section")
1518

19+
1620
class PatentSection(Section):
1721
def describe(self):
1822
print("Patent Section")
1923

24+
2025
class PublicationSection(Section):
2126
def describe(self):
2227
print("Publication Section")
2328

2429

25-
2630
class Profile(metaclass=ABCMeta):
2731
def __init__(self):
28-
self.sections=[]
32+
self.sections = []
2933
self.createProfile()
3034

3135
@abstractmethod
@@ -38,12 +42,14 @@ def getSections(self):
3842
def addSections(self, section):
3943
self.sections.append(section)
4044

45+
4146
class linkedin(Profile):
4247
def createProfile(self):
4348
self.addSections(PersonalSection())
4449
self.addSections(PatentSection())
4550
self.addSections(PublicationSection())
4651

52+
4753
class facebook(Profile):
4854
def createProfile(self):
4955
self.addSections(PersonalSection())
@@ -54,4 +60,4 @@ def createProfile(self):
5460
profile_type = input("Which Profile you'd like to create? [Linkedin or Facebook]")
5561
profile = eval(profile_type.lower())()
5662
print("Creating Profile..", type(profile).__name__)
57-
print("Profile has sections --", profile.getSections())
63+
print("Profile has sections --", profile.getSections())
Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,28 @@
11
from abc import ABCMeta, abstractmethod
22

3+
34
class Animal(metaclass=ABCMeta):
45
@abstractmethod
56
def do_say(self):
67
pass
78

9+
810
class Dog(Animal):
911
def do_say(self):
1012
print("Au!!")
1113

14+
1215
class Cat(Animal):
1316
def do_say(self):
1417
print("Miau!!")
1518

19+
1620
class ForestFactory(object):
1721
def make_sound(self, object_type):
1822
return eval(object_type)().do_say()
1923

2024

21-
if __name__=='__main__':
22-
ff=ForestFactory()
23-
animal=input("Which animal should make sound Dog or Cat?")
24-
ff.make_sound(animal)
25+
if __name__ == '__main__':
26+
ff = ForestFactory()
27+
animal = input("Which animal should make sound Dog or Cat?")
28+
ff.make_sound(animal)

design_patterns/observer/code.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ class Subject:
22
def __init__(self):
33
self.__observers = []
44

5-
def register(self,observer):
5+
def register(self, observer):
66
self.__observers.append(observer)
77

88
def notifyAll(self, *args, **kwargs):
@@ -15,18 +15,19 @@ def __init__(self, subject):
1515
subject.register(self)
1616

1717
def listen(self, subject, *args):
18-
print(type(self).__name__,':: Got',args,'From',subject)
18+
print(type(self).__name__, ':: Got', args, 'From', subject)
1919

2020

2121
class Observer2:
2222
def __init__(self, subject):
2323
subject.register(self)
2424

2525
def listen(self, subject, *args):
26-
print(type(self).__name__,':: Got',args,'From',subject)
26+
print(type(self).__name__, ':: Got', args, 'From', subject)
2727

2828

29-
subject = Subject()
30-
observer1 = Observer1(subject)
31-
observer2 = Observer2(subject)
32-
subject.notifyAll('notification')
29+
if __name__ == "__main__":
30+
subject = Subject()
31+
observer1 = Observer1(subject)
32+
observer2 = Observer2(subject)
33+
subject.notifyAll('notification')

0 commit comments

Comments
 (0)