mirror of
https://github.com/rjNemo/design-patterns
synced 2026-06-06 10:36:39 +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):
|
||||
def handle(self, request: Any) -> Optional[str]:
|
||||
if request == 'Banana':
|
||||
if request == "Banana":
|
||||
return f"Monkey: I'll eat the {request}"
|
||||
return super().handle(request)
|
||||
|
||||
|
||||
class SquirrelHandler(AbstractHandler):
|
||||
def handle(self, request: Any) -> Optional[str]:
|
||||
if request == 'Nut':
|
||||
if request == "Nut":
|
||||
return f"Squirrel: I'll eat the {request}"
|
||||
return super().handle(request)
|
||||
|
||||
|
||||
class DogHandler(AbstractHandler):
|
||||
def handle(self, request: Any) -> Optional[str]:
|
||||
if request == 'MeatBall':
|
||||
if request == "MeatBall":
|
||||
return f"Dog: I'll eat the {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
|
||||
|
||||
|
||||
|
|
@ -18,7 +22,7 @@ def client_code(handler: Handler):
|
|||
print(f" {food} was left untouched.", end="")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
monkey = MonkeyHandler()
|
||||
squirrel = SquirrelHandler()
|
||||
dog = DogHandler()
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ class SimpleCommand(Command):
|
|||
|
||||
def execute(self) -> None:
|
||||
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):
|
||||
|
|
@ -36,6 +37,8 @@ class ComplexCommand(Command):
|
|||
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_else(self._b)
|
||||
|
|
|
|||
|
|
@ -5,12 +5,11 @@ from behavioral.command.commands import SimpleCommand, ComplexCommand
|
|||
from behavioral.command.invoker import Invoker
|
||||
from behavioral.command.receiver import Receiver
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
invoker = Invoker()
|
||||
invoker.set_on_start(SimpleCommand("Say hi"))
|
||||
|
||||
receiver = Receiver()
|
||||
invoker.set_on_finish(ComplexCommand(
|
||||
receiver, "Send email", "Save report"))
|
||||
invoker.set_on_finish(ComplexCommand(receiver, "Send email", "Save report"))
|
||||
|
||||
invoker.do_something_important()
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ from behavioral.memento.memento import Memento
|
|||
|
||||
|
||||
class ConcreteMemento(Memento):
|
||||
|
||||
def __init__(self, state: str) -> None:
|
||||
self._state = state
|
||||
self._date = str(datetime.now())[:19]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
||||
from creational.abstract_factory.products import ConcreteProductA1, \
|
||||
ConcreteProductB1, ConcreteProductA2, ConcreteProductB2
|
||||
from creational.abstract_factory.products import (
|
||||
ConcreteProductA1,
|
||||
ConcreteProductB1,
|
||||
ConcreteProductA2,
|
||||
ConcreteProductB2,
|
||||
)
|
||||
|
||||
|
||||
class ConcreteFactory1(AbstractFactory):
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
"""The client code can work with any concrete factory class."""
|
||||
|
||||
from creational.abstract_factory.AbstractFactory import AbstractFactory
|
||||
from creational.abstract_factory.factories import ConcreteFactory1, \
|
||||
ConcreteFactory2
|
||||
from creational.abstract_factory.factories import ConcreteFactory1, ConcreteFactory2
|
||||
|
||||
|
||||
def client_code(factory: AbstractFactory) -> None:
|
||||
|
|
|
|||
|
|
@ -4,8 +4,7 @@ product's type.
|
|||
"""
|
||||
|
||||
from creational.factory_method.ICreator import ICreator
|
||||
from creational.factory_method.products import ConcreteProduct1, \
|
||||
ConcreteProduct2
|
||||
from creational.factory_method.products import ConcreteProduct1, ConcreteProduct2
|
||||
|
||||
|
||||
class ConcreteCreator1(ICreator):
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
from creational.factory_method.ICreator import ICreator
|
||||
from creational.factory_method.creators import ConcreteCreator1, \
|
||||
ConcreteCreator2
|
||||
from creational.factory_method.creators import ConcreteCreator1, ConcreteCreator2
|
||||
|
||||
|
||||
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
|
||||
# nested objects.
|
||||
new = self.__class__(
|
||||
self.some_int, some_list_of_objects, some_circular_ref)
|
||||
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
|
||||
new.__dict__.update(self.__dict__)
|
||||
|
||||
return new
|
||||
|
|
@ -63,8 +62,7 @@ class SomeComponent:
|
|||
some_circular_ref = copy.deepcopy(self.some_circular_ref, memo)
|
||||
# Then, let's clone the object itself, using the prepared clones of the
|
||||
# nested objects.
|
||||
new = self.__class__(
|
||||
self.some_int, some_list_of_objects, some_circular_ref)
|
||||
new = self.__class__(self.some_int, some_list_of_objects, some_circular_ref)
|
||||
|
||||
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.
|
||||
"""
|
||||
from structural.bridge.abstractions import Abstraction
|
||||
from structural.bridge.implementations import ConcreteImplementationA, \
|
||||
ConcreteImplementationB
|
||||
from structural.bridge.implementations import (
|
||||
ConcreteImplementationA,
|
||||
ConcreteImplementationB,
|
||||
)
|
||||
|
||||
|
||||
def client_code(abstraction: Abstraction) -> None:
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
from structural.decorator.component import Component
|
||||
from structural.decorator.concrete_component import ConcreteComponent
|
||||
from structural.decorator.concrete_decorators import ConcreteDecoratorA, \
|
||||
ConcreteDecoratorB
|
||||
from structural.decorator.concrete_decorators import (
|
||||
ConcreteDecoratorA,
|
||||
ConcreteDecoratorB,
|
||||
)
|
||||
|
||||
|
||||
def client_code(component: Component):
|
||||
|
|
@ -11,10 +13,10 @@ def client_code(component: Component):
|
|||
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...
|
||||
simple = ConcreteComponent()
|
||||
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
|
||||
of a subsystem's capabilities.
|
||||
"""
|
||||
results = []
|
||||
results.append("Facade initializes subsystems:")
|
||||
results.append(self._subsystem1.operation1())
|
||||
results.append(self._subsystem2.operation1())
|
||||
results.append("Facade orders subsystems to perform the action:")
|
||||
results.append(self._subsystem1.operation_n())
|
||||
results.append(self._subsystem2.operation_z())
|
||||
results = [
|
||||
"Facade initializes subsystems:",
|
||||
self._subsystem1.operation1(),
|
||||
self._subsystem2.operation1(),
|
||||
"Facade orders subsystems to perform the action:",
|
||||
self._subsystem1.operation_n(),
|
||||
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.
|
||||
"""
|
||||
|
||||
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.
|
||||
# In this case, it might be worthwhile to initialize the Facade with these
|
||||
# objects instead of letting the Facade create new instances.
|
||||
|
|
|
|||
|
|
@ -16,5 +16,4 @@ class Flyweight:
|
|||
def operation(self, unique_state: List[str]) -> None:
|
||||
s = json.dumps(self._shared_state)
|
||||
u = json.dumps(unique_state)
|
||||
print(f"Flyweight: Displaying shared ({s}) and unique ({u}) state.",
|
||||
end="")
|
||||
print(f"Flyweight: Displaying shared ({s}) and unique ({u}) state.", end="")
|
||||
|
|
|
|||
|
|
@ -1,9 +1,14 @@
|
|||
from structural.flyweight.flyweight_factory import FlyweightFactory
|
||||
|
||||
|
||||
def add_car_to_police_database(factory: FlyweightFactory, plates: str,
|
||||
owner: str, brand: str, model: str,
|
||||
color: str) -> None:
|
||||
def add_car_to_police_database(
|
||||
factory: FlyweightFactory,
|
||||
plates: str,
|
||||
owner: str,
|
||||
brand: str,
|
||||
model: str,
|
||||
color: str,
|
||||
) -> None:
|
||||
|
||||
print("\n\nClient: Adding a car to database.")
|
||||
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])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
"""
|
||||
The client code usually creates a bunch of pre-populated flyweights in the
|
||||
initialization stage of the application.
|
||||
"""
|
||||
factory = FlyweightFactory([
|
||||
["Chevrolet", "Camaro2018", "pink"],
|
||||
["Mercedes Benz", "C300", "black"],
|
||||
["Mercedes Benz", "C500", "red"],
|
||||
["BMW", "M5", "red"],
|
||||
["BMW", "X6", "white"],
|
||||
])
|
||||
factory = FlyweightFactory(
|
||||
[
|
||||
["Chevrolet", "Camaro2018", "pink"],
|
||||
["Mercedes Benz", "C300", "black"],
|
||||
["Mercedes Benz", "C500", "red"],
|
||||
["BMW", "M5", "red"],
|
||||
["BMW", "X6", "white"],
|
||||
]
|
||||
)
|
||||
|
||||
factory.list_flyweights()
|
||||
|
||||
add_car_to_police_database(
|
||||
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", "M5", "red")
|
||||
add_car_to_police_database(factory, "CL234IR", "James Doe", "BMW", "X1", "red")
|
||||
|
||||
print("\n")
|
||||
|
||||
|
|
|
|||
|
|
@ -15,11 +15,11 @@ def client_code(subject: Subject) -> None:
|
|||
subject.request()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
print("Client: Executing the client code with a real subject:")
|
||||
real_subject = RealSubject()
|
||||
client_code(real_subject)
|
||||
print('')
|
||||
print("")
|
||||
print("Client: Executing the same client code with a proxy:")
|
||||
proxy = Proxy(real_subject)
|
||||
client_code(proxy)
|
||||
|
|
|
|||
Loading…
Reference in a new issue