mirror of
https://github.com/rjNemo/design-patterns
synced 2026-06-11 21:16:40 +00:00
reformat using black
This commit is contained in:
parent
b9a7028567
commit
1811e73028
17 changed files with 71 additions and 58 deletions
|
|
@ -9,20 +9,20 @@ from behavioral.chain_responsibility.abstract_handler import AbstractHandler
|
||||||
|
|
||||||
class MonkeyHandler(AbstractHandler):
|
class MonkeyHandler(AbstractHandler):
|
||||||
def handle(self, request: Any) -> Optional[str]:
|
def handle(self, request: Any) -> Optional[str]:
|
||||||
if request == 'Banana':
|
if request == "Banana":
|
||||||
return f"Monkey: I'll eat the {request}"
|
return f"Monkey: I'll eat the {request}"
|
||||||
return super().handle(request)
|
return super().handle(request)
|
||||||
|
|
||||||
|
|
||||||
class SquirrelHandler(AbstractHandler):
|
class SquirrelHandler(AbstractHandler):
|
||||||
def handle(self, request: Any) -> Optional[str]:
|
def handle(self, request: Any) -> Optional[str]:
|
||||||
if request == 'Nut':
|
if request == "Nut":
|
||||||
return f"Squirrel: I'll eat the {request}"
|
return f"Squirrel: I'll eat the {request}"
|
||||||
return super().handle(request)
|
return super().handle(request)
|
||||||
|
|
||||||
|
|
||||||
class DogHandler(AbstractHandler):
|
class DogHandler(AbstractHandler):
|
||||||
def handle(self, request: Any) -> Optional[str]:
|
def handle(self, request: Any) -> Optional[str]:
|
||||||
if request == 'MeatBall':
|
if request == "MeatBall":
|
||||||
return f"Dog: I'll eat the {request}"
|
return f"Dog: I'll eat the {request}"
|
||||||
return super().handle(request)
|
return super().handle(request)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,8 @@
|
||||||
from behavioral.chain_responsibility.concrete_handlers import MonkeyHandler, SquirrelHandler, DogHandler
|
from behavioral.chain_responsibility.concrete_handlers import (
|
||||||
|
MonkeyHandler,
|
||||||
|
SquirrelHandler,
|
||||||
|
DogHandler,
|
||||||
|
)
|
||||||
from behavioral.chain_responsibility.handler import Handler
|
from behavioral.chain_responsibility.handler import Handler
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -18,7 +22,7 @@ def client_code(handler: Handler):
|
||||||
print(f" {food} was left untouched.", end="")
|
print(f" {food} was left untouched.", end="")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
monkey = MonkeyHandler()
|
monkey = MonkeyHandler()
|
||||||
squirrel = SquirrelHandler()
|
squirrel = SquirrelHandler()
|
||||||
dog = DogHandler()
|
dog = DogHandler()
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,8 @@ class SimpleCommand(Command):
|
||||||
|
|
||||||
def execute(self) -> None:
|
def execute(self) -> None:
|
||||||
print(
|
print(
|
||||||
f"SimpleCommand: See, I can do simple things like printing ({self._payload})")
|
f"SimpleCommand: See, I can do simple things like printing ({self._payload})"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ComplexCommand(Command):
|
class ComplexCommand(Command):
|
||||||
|
|
@ -36,6 +37,8 @@ class ComplexCommand(Command):
|
||||||
Commands can delegate to any methods of a receiver.
|
Commands can delegate to any methods of a receiver.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
print("ComplexCommand: Complex stuff should be done by a receiver object", end="")
|
print(
|
||||||
|
"ComplexCommand: Complex stuff should be done by a receiver object", end=""
|
||||||
|
)
|
||||||
self._receiver.do_something(self._a)
|
self._receiver.do_something(self._a)
|
||||||
self._receiver.do_something_else(self._b)
|
self._receiver.do_something_else(self._b)
|
||||||
|
|
|
||||||
|
|
@ -5,12 +5,11 @@ from behavioral.command.commands import SimpleCommand, ComplexCommand
|
||||||
from behavioral.command.invoker import Invoker
|
from behavioral.command.invoker import Invoker
|
||||||
from behavioral.command.receiver import Receiver
|
from behavioral.command.receiver import Receiver
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
invoker = Invoker()
|
invoker = Invoker()
|
||||||
invoker.set_on_start(SimpleCommand("Say hi"))
|
invoker.set_on_start(SimpleCommand("Say hi"))
|
||||||
|
|
||||||
receiver = Receiver()
|
receiver = Receiver()
|
||||||
invoker.set_on_finish(ComplexCommand(
|
invoker.set_on_finish(ComplexCommand(receiver, "Send email", "Save report"))
|
||||||
receiver, "Send email", "Save report"))
|
|
||||||
|
|
||||||
invoker.do_something_important()
|
invoker.do_something_important()
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@ from behavioral.memento.memento import Memento
|
||||||
|
|
||||||
|
|
||||||
class ConcreteMemento(Memento):
|
class ConcreteMemento(Memento):
|
||||||
|
|
||||||
def __init__(self, state: str) -> None:
|
def __init__(self, state: str) -> None:
|
||||||
self._state = state
|
self._state = state
|
||||||
self._date = str(datetime.now())[:19]
|
self._date = str(datetime.now())[:19]
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,10 @@
|
||||||
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
||||||
from creational.abstract_factory.products import ConcreteProductA1, \
|
from creational.abstract_factory.products import (
|
||||||
ConcreteProductB1, ConcreteProductA2, ConcreteProductB2
|
ConcreteProductA1,
|
||||||
|
ConcreteProductB1,
|
||||||
|
ConcreteProductA2,
|
||||||
|
ConcreteProductB2,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ConcreteFactory1(AbstractFactory):
|
class ConcreteFactory1(AbstractFactory):
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
"""The client code can work with any concrete factory class."""
|
"""The client code can work with any concrete factory class."""
|
||||||
|
|
||||||
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
||||||
from creational.abstract_factory.factories import ConcreteFactory1, \
|
from creational.abstract_factory.factories import ConcreteFactory1, ConcreteFactory2
|
||||||
ConcreteFactory2
|
|
||||||
|
|
||||||
|
|
||||||
def client_code(factory: AbstractFactory) -> None:
|
def client_code(factory: AbstractFactory) -> None:
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,7 @@ product's type.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from creational.factory_method.ICreator import ICreator
|
from creational.factory_method.ICreator import ICreator
|
||||||
from creational.factory_method.products import ConcreteProduct1, \
|
from creational.factory_method.products import ConcreteProduct1, ConcreteProduct2
|
||||||
ConcreteProduct2
|
|
||||||
|
|
||||||
|
|
||||||
class ConcreteCreator1(ICreator):
|
class ConcreteCreator1(ICreator):
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
from creational.factory_method.ICreator import ICreator
|
from creational.factory_method.ICreator import ICreator
|
||||||
from creational.factory_method.creators import ConcreteCreator1, \
|
from creational.factory_method.creators import ConcreteCreator1, ConcreteCreator2
|
||||||
ConcreteCreator2
|
|
||||||
|
|
||||||
|
|
||||||
def client_code(creator: ICreator) -> None:
|
def client_code(creator: ICreator) -> None:
|
||||||
|
|
|
||||||
|
|
@ -39,8 +39,7 @@ class SomeComponent:
|
||||||
|
|
||||||
# Then, let's clone the object itself, using the prepared clones of the
|
# Then, let's clone the object itself, using the prepared clones of the
|
||||||
# nested objects.
|
# nested objects.
|
||||||
new = self.__class__(
|
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
|
||||||
self.some_int, some_list_of_objects, some_circular_ref)
|
|
||||||
new.__dict__.update(self.__dict__)
|
new.__dict__.update(self.__dict__)
|
||||||
|
|
||||||
return new
|
return new
|
||||||
|
|
@ -63,8 +62,7 @@ class SomeComponent:
|
||||||
some_circular_ref = copy.deepcopy(self.some_circular_ref, memo)
|
some_circular_ref = copy.deepcopy(self.some_circular_ref, memo)
|
||||||
# Then, let's clone the object itself, using the prepared clones of the
|
# Then, let's clone the object itself, using the prepared clones of the
|
||||||
# nested objects.
|
# nested objects.
|
||||||
new = self.__class__(
|
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
|
||||||
self.some_int, some_list_of_objects, some_circular_ref)
|
|
||||||
|
|
||||||
new.__dict__ = copy.deepcopy(self.__dict__, memo)
|
new.__dict__ = copy.deepcopy(self.__dict__, memo)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,10 @@ The client code should be able to work with any pre-configured abstraction-
|
||||||
implementation combination.
|
implementation combination.
|
||||||
"""
|
"""
|
||||||
from structural.bridge.abstractions import Abstraction
|
from structural.bridge.abstractions import Abstraction
|
||||||
from structural.bridge.implementations import ConcreteImplementationA, \
|
from structural.bridge.implementations import (
|
||||||
ConcreteImplementationB
|
ConcreteImplementationA,
|
||||||
|
ConcreteImplementationB,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def client_code(abstraction: Abstraction) -> None:
|
def client_code(abstraction: Abstraction) -> None:
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
from structural.decorator.component import Component
|
from structural.decorator.component import Component
|
||||||
from structural.decorator.concrete_component import ConcreteComponent
|
from structural.decorator.concrete_component import ConcreteComponent
|
||||||
from structural.decorator.concrete_decorators import ConcreteDecoratorA, \
|
from structural.decorator.concrete_decorators import (
|
||||||
ConcreteDecoratorB
|
ConcreteDecoratorA,
|
||||||
|
ConcreteDecoratorB,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def client_code(component: Component):
|
def client_code(component: Component):
|
||||||
|
|
@ -11,10 +13,10 @@ def client_code(component: Component):
|
||||||
with.
|
with.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
print(f"RESULT: {component.operation()}", end='')
|
print(f"RESULT: {component.operation()}", end="")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
# This way the client code can support both simple components...
|
# This way the client code can support both simple components...
|
||||||
simple = ConcreteComponent()
|
simple = ConcreteComponent()
|
||||||
print("Client: I've got a simple component:")
|
print("Client: I've got a simple component:")
|
||||||
|
|
|
||||||
|
|
@ -25,12 +25,13 @@ class Facade:
|
||||||
functionality of the subsystems. However, clients get only to a fraction
|
functionality of the subsystems. However, clients get only to a fraction
|
||||||
of a subsystem's capabilities.
|
of a subsystem's capabilities.
|
||||||
"""
|
"""
|
||||||
results = []
|
results = [
|
||||||
results.append("Facade initializes subsystems:")
|
"Facade initializes subsystems:",
|
||||||
results.append(self._subsystem1.operation1())
|
self._subsystem1.operation1(),
|
||||||
results.append(self._subsystem2.operation1())
|
self._subsystem2.operation1(),
|
||||||
results.append("Facade orders subsystems to perform the action:")
|
"Facade orders subsystems to perform the action:",
|
||||||
results.append(self._subsystem1.operation_n())
|
self._subsystem1.operation_n(),
|
||||||
results.append(self._subsystem2.operation_z())
|
self._subsystem2.operation_z(),
|
||||||
|
]
|
||||||
|
|
||||||
return '\n'.join(results)
|
return "\n".join(results)
|
||||||
|
|
|
||||||
|
|
@ -10,10 +10,10 @@ def client_code(facade: Facade) -> None:
|
||||||
subsystem. This approach lets you keep the complexity under control.
|
subsystem. This approach lets you keep the complexity under control.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
print(facade.operation(), end='')
|
print(facade.operation(), end="")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
# The client code may have some of the subsystem's objects already created.
|
# The client code may have some of the subsystem's objects already created.
|
||||||
# In this case, it might be worthwhile to initialize the Facade with these
|
# In this case, it might be worthwhile to initialize the Facade with these
|
||||||
# objects instead of letting the Facade create new instances.
|
# objects instead of letting the Facade create new instances.
|
||||||
|
|
|
||||||
|
|
@ -16,5 +16,4 @@ class Flyweight:
|
||||||
def operation(self, unique_state: List[str]) -> None:
|
def operation(self, unique_state: List[str]) -> None:
|
||||||
s = json.dumps(self._shared_state)
|
s = json.dumps(self._shared_state)
|
||||||
u = json.dumps(unique_state)
|
u = json.dumps(unique_state)
|
||||||
print(f"Flyweight: Displaying shared ({s}) and unique ({u}) state.",
|
print(f"Flyweight: Displaying shared ({s}) and unique ({u}) state.", end="")
|
||||||
end="")
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,14 @@
|
||||||
from structural.flyweight.flyweight_factory import FlyweightFactory
|
from structural.flyweight.flyweight_factory import FlyweightFactory
|
||||||
|
|
||||||
|
|
||||||
def add_car_to_police_database(factory: FlyweightFactory, plates: str,
|
def add_car_to_police_database(
|
||||||
owner: str, brand: str, model: str,
|
factory: FlyweightFactory,
|
||||||
color: str) -> None:
|
plates: str,
|
||||||
|
owner: str,
|
||||||
|
brand: str,
|
||||||
|
model: str,
|
||||||
|
color: str,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
print("\n\nClient: Adding a car to database.")
|
print("\n\nClient: Adding a car to database.")
|
||||||
flyweight = factory.get_flyweight([brand, model, color])
|
flyweight = factory.get_flyweight([brand, model, color])
|
||||||
|
|
@ -12,25 +17,25 @@ def add_car_to_police_database(factory: FlyweightFactory, plates: str,
|
||||||
flyweight.operation([plates, owner])
|
flyweight.operation([plates, owner])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
"""
|
"""
|
||||||
The client code usually creates a bunch of pre-populated flyweights in the
|
The client code usually creates a bunch of pre-populated flyweights in the
|
||||||
initialization stage of the application.
|
initialization stage of the application.
|
||||||
"""
|
"""
|
||||||
factory = FlyweightFactory([
|
factory = FlyweightFactory(
|
||||||
["Chevrolet", "Camaro2018", "pink"],
|
[
|
||||||
["Mercedes Benz", "C300", "black"],
|
["Chevrolet", "Camaro2018", "pink"],
|
||||||
["Mercedes Benz", "C500", "red"],
|
["Mercedes Benz", "C300", "black"],
|
||||||
["BMW", "M5", "red"],
|
["Mercedes Benz", "C500", "red"],
|
||||||
["BMW", "X6", "white"],
|
["BMW", "M5", "red"],
|
||||||
])
|
["BMW", "X6", "white"],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
factory.list_flyweights()
|
factory.list_flyweights()
|
||||||
|
|
||||||
add_car_to_police_database(
|
add_car_to_police_database(factory, "CL234IR", "James Doe", "BMW", "M5", "red")
|
||||||
factory, "CL234IR", "James Doe", "BMW", "M5", "red")
|
add_car_to_police_database(factory, "CL234IR", "James Doe", "BMW", "X1", "red")
|
||||||
add_car_to_police_database(
|
|
||||||
factory, "CL234IR", "James Doe", "BMW", "X1", "red")
|
|
||||||
|
|
||||||
print("\n")
|
print("\n")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -15,11 +15,11 @@ def client_code(subject: Subject) -> None:
|
||||||
subject.request()
|
subject.request()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
print("Client: Executing the client code with a real subject:")
|
print("Client: Executing the client code with a real subject:")
|
||||||
real_subject = RealSubject()
|
real_subject = RealSubject()
|
||||||
client_code(real_subject)
|
client_code(real_subject)
|
||||||
print('')
|
print("")
|
||||||
print("Client: Executing the same client code with a proxy:")
|
print("Client: Executing the same client code with a proxy:")
|
||||||
proxy = Proxy(real_subject)
|
proxy = Proxy(real_subject)
|
||||||
client_code(proxy)
|
client_code(proxy)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue