Skip to content

Commit b330efd

Browse files
committed
Fix long (>80 characters) lines
1 parent 8b77a1d commit b330efd

18 files changed

Lines changed: 134 additions & 117 deletions

File tree

src/AbstractFactory/Structural/main.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,15 @@ class AbstractFactory(ABC):
2121
different abstract products. These products are called a family and are
2222
related by a high-level theme or concept. Products of one family are usually
2323
able to collaborate among themselves. A family of products may have several
24-
variants, but the products of one variant are incompatible with products
25-
of another.
26-
27-
RU: Интерфейс Абстрактной Фабрики объявляет набор методов, которые возвращают
28-
различные абстрактные продукты. Эти продукты называются семейством и связаны
29-
темой или концепцией высокого уровня. Продукты одного семейства обычно могут
30-
взаимодействовать между собой. Семейство продуктов может иметь несколько
31-
вариаций, но продукты одной вариации несовместимы с продуктами другой.
24+
variants, but the products of one variant are incompatible with products of
25+
another.
26+
27+
RU: Интерфейс Абстрактной Фабрики объявляет набор методов, которые
28+
возвращают различные абстрактные продукты. Эти продукты называются
29+
семейством и связаны темой или концепцией высокого уровня. Продукты одного
30+
семейства обычно могут взаимодействовать между собой. Семейство продуктов
31+
может иметь несколько вариаций, но продукты одной вариации несовместимы с
32+
продуктами другой.
3233
"""
3334
@abstractmethod
3435
def create_product_a(self) -> AbstractProductA:
@@ -109,9 +110,9 @@ def useful_function_a(self) -> str:
109110

110111
class AbstractProductB(ABC):
111112
"""
112-
EN: Here's the the base interface of another product. All products can interact with
113-
each other, but proper interaction is possible only between products of the
114-
same concrete variant.
113+
EN: Here's the the base interface of another product. All products can
114+
interact with each other, but proper interaction is possible only between
115+
products of the same concrete variant.
115116
116117
RU: Базовый интерфейс другого продукта. Все продукты могут взаимодействовать
117118
друг с другом, но правильное взаимодействие возможно только между продуктами

src/Adapter/Structural/main.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
class Target():
1616
"""
17-
EN: The Target defines the domain-specific interface used by the client code.
17+
EN: The Target defines the domain-specific interface used by the client
18+
code.
1819
1920
RU: Целевой класс объявляет интерфейс, с которым может работать клиентский
2021
код.
@@ -27,8 +28,8 @@ def request(self) -> str:
2728
class Adaptee:
2829
"""
2930
EN: The Adaptee contains some useful behavior, but its interface is
30-
incompatible with the existing client code. The Adaptee needs some adaptation
31-
before the client code can use it.
31+
incompatible with the existing client code. The Adaptee needs some
32+
adaptation before the client code can use it.
3233
3334
RU: Адаптируемый класс содержит некоторое полезное поведение, но его
3435
интерфейс несовместим с существующим клиентским кодом. Адаптируемый класс

src/Bridge/Structural/main.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def __init__(self, implementation: Implementation) -> None:
4242
self.implementation = implementation
4343

4444
def operation(self) -> str:
45-
return f"Abstraction: Base operation with:\n{self.implementation.operation_implementation()}"
45+
return (f"Abstraction: Base operation with:\n"
46+
f"{self.implementation.operation_implementation()}")
4647

4748

4849
class ExtendedAbstraction(Abstraction):
@@ -54,7 +55,8 @@ class ExtendedAbstraction(Abstraction):
5455
"""
5556

5657
def operation(self) -> str:
57-
return f"ExtendedAbstraction: Extended operation with:\n{self.implementation.operation_implementation()}"
58+
return (f"ExtendedAbstraction: Extended operation with:\n"
59+
f"{self.implementation.operation_implementation()}")
5860

5961

6062
class Implementation(ABC):
@@ -103,8 +105,8 @@ def client_code(abstraction: Abstraction) -> None:
103105
depend on the Abstraction class. This way the client code can support any
104106
abstraction-implementation combination.
105107
106-
RU: За исключением этапа инициализации, когда объект Абстракции связывается с
107-
определённым объектом Реализации, клиентский код должен зависеть только от
108+
RU: За исключением этапа инициализации, когда объект Абстракции связывается
109+
с определённым объектом Реализации, клиентский код должен зависеть только от
108110
класса Абстракции. Таким образом, клиентский код может поддерживать любую
109111
комбинацию абстракции и реализации.
110112
"""

src/Builder/Structural/main.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,9 @@ class Product1():
125125
продукты достаточно сложны и требуют обширной конфигурации.
126126
127127
В отличие от других порождающих паттернов, различные конкретные строители
128-
могут производить несвязанные продукты. Другими словами, результаты различных
129-
строителей могут не всегда следовать одному и тому же интерфейсу.
128+
могут производить несвязанные продукты. Другими словами, результаты
129+
различных строителей могут не всегда следовать одному и тому же
130+
интерфейсу.
130131
"""
131132

132133
def __init__(self) -> None:
@@ -192,8 +193,8 @@ def build_full_featured_product(self) -> None:
192193
if __name__ == "__main__":
193194
"""
194195
EN: The client code creates a builder object, passes it to the director and
195-
then initiates the construction process. The end result is retrieved from the
196-
builder object.
196+
then initiates the construction process. The end result is retrieved from
197+
the builder object.
197198
198199
RU: Клиентский код создаёт объект-строитель, передаёт его директору, а затем
199200
инициирует процесс построения. Конечный результат извлекается из

src/ChainOfResponsibility/Structural/main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ class Handler(ABC):
2323
EN: The Handler interface declares a method for building the chain of
2424
handlers. It also declares a method for executing a request.
2525
26-
RU: Интерфейс Обработчика объявляет метод построения цепочки обработчиков. Он
27-
также объявляет метод для выполнения запроса.
26+
RU: Интерфейс Обработчика объявляет метод построения цепочки обработчиков.
27+
Он также объявляет метод для выполнения запроса.
2828
"""
2929

3030
@abstractmethod
@@ -129,7 +129,7 @@ def client_code(handler: Handler) -> None:
129129
"""
130130
EN: The client should be able to send a request to any handler, not just the
131131
first one in the chain.
132-
132+
133133
RU: Клиент должен иметь возможность отправлять запрос любому обработчику, а
134134
не только первому в цепочке.
135135
"""

src/Command/Structural/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ def __init__(self, payload: str) -> None:
4040
self._payload = payload
4141

4242
def execute(self) -> None:
43-
print(f"SimpleCommand: See, I can do simple things like printing ({self._payload})")
43+
print(f"SimpleCommand: See, I can do simple things like printing"
44+
f"({self._payload})")
4445

4546

4647
class ComplexCommand(Command):

src/Composite/Structural/main.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ def remove(self, component: Component) -> None:
6868

6969
def is_composite(self) -> bool:
7070
"""
71-
EN: You can provide a method that lets the client code figure out whether
72-
a component can bear children.
71+
EN: You can provide a method that lets the client code figure out
72+
whether a component can bear children.
7373
7474
RU: Вы можете предоставить метод, который позволит клиентскому коду
7575
понять, может ли компонент иметь вложенные объекты.
@@ -80,8 +80,8 @@ def is_composite(self) -> bool:
8080
@abstractmethod
8181
def operation(self) -> str:
8282
"""
83-
EN: The base Component may implement some default behavior or leave it to
84-
concrete classes (by declaring the method containing the behavior as
83+
EN: The base Component may implement some default behavior or leave it
84+
to concrete classes (by declaring the method containing the behavior as
8585
"abstract").
8686
8787
RU: Базовый Компонент может сам реализовать некоторое поведение по
@@ -118,8 +118,8 @@ class Composite(Component):
118118
children and then "sum-up" the result.
119119
120120
RU: Класс Контейнер содержит сложные компоненты, которые могут иметь
121-
вложенные компоненты. Обычно объекты Контейнеры делегируют фактическую работу
122-
своим детям, а затем «суммируют» результат.
121+
вложенные компоненты. Обычно объекты Контейнеры делегируют фактическую
122+
работу своим детям, а затем «суммируют» результат.
123123
"""
124124

125125
def __init__(self) -> None:
@@ -176,8 +176,8 @@ def client_code(component: Component) -> None:
176176
def client_code2(component1: Component, component2: Component) -> None:
177177
"""
178178
EN: Thanks to the fact that the child-management operations are declared in
179-
the base Component class, the client code can work with any component, simple
180-
or complex, without depending on their concrete classes.
179+
the base Component class, the client code can work with any component,
180+
simple or complex, without depending on their concrete classes.
181181
182182
RU: Благодаря тому, что операции управления потомками объявлены в базовом
183183
классе Компонента, клиентский код может работать как с простыми, так и со

src/Facade/Structural/main.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,17 @@ class Facade:
2424
managing their lifecycle. All of this shields the client from the undesired
2525
complexity of the subsystem.
2626
27-
RU: Класс Фасада предоставляет простой интерфейс для сложной логики одной или
28-
нескольких подсистем. Фасад делегирует запросы клиентов соответствующим
27+
RU: Класс Фасада предоставляет простой интерфейс для сложной логики одной
28+
или нескольких подсистем. Фасад делегирует запросы клиентов соответствующим
2929
объектам внутри подсистемы. Фасад также отвечает за управление их жизненным
3030
циклом. Все это защищает клиента от нежелательной сложности подсистемы.
3131
"""
3232

3333
def __init__(self, subsystem1: Subsystem1, subsystem2: Subsystem2) -> None:
3434
"""
3535
EN: Depending on your application's needs, you can provide the Facade
36-
with existing subsystem objects or force the Facade to create them on its
37-
own.
36+
with existing subsystem objects or force the Facade to create them on
37+
its own.
3838
3939
RU: В зависимости от потребностей вашего приложения вы можете
4040
предоставить Фасаду существующие объекты подсистемы или заставить Фасад
@@ -103,14 +103,14 @@ def operation_z(self) -> str:
103103
def client_code(facade: Facade) -> None:
104104
"""
105105
EN: The client code works with complex subsystems through a simple interface
106-
provided by the Facade. When a facade manages the lifecycle of the subsystem,
107-
the client might not even know about the existence of the subsystem. This
108-
approach lets you keep the complexity under control.
109-
110-
RU: Клиентский код работает со сложными подсистемами через простой интерфейс,
111-
предоставляемый Фасадом. Когда фасад управляет жизненным циклом подсистемы,
112-
клиент может даже не знать о существовании подсистемы. Такой подход позволяет
113-
держать сложность под контролем.
106+
provided by the Facade. When a facade manages the lifecycle of the
107+
subsystem, the client might not even know about the existence of the
108+
subsystem. This approach lets you keep the complexity under control.
109+
110+
RU: Клиентский код работает со сложными подсистемами через простой
111+
интерфейс, предоставляемый Фасадом. Когда фасад управляет жизненным циклом
112+
подсистемы, клиент может даже не знать о существовании подсистемы. Такой
113+
подход позволяет держать сложность под контролем.
114114
"""
115115

116116
print(facade.operation(), end="")

src/FactoryMethod/Structural/main.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ class Creator(ABC):
3131
@abstractmethod
3232
def factory_method(self):
3333
"""
34-
EN: Note that the Creator may also provide some default implementation of
35-
the factory method.
34+
EN: Note that the Creator may also provide some default implementation
35+
of the factory method.
3636
3737
RU: Обратите внимание, что Создатель может также обеспечить реализацию
3838
фабричного метода по умолчанию.
@@ -50,10 +50,10 @@ def some_operation(self) -> str:
5050
5151
RU: Также заметьте, что, несмотря на название, основная обязанность
5252
Создателя не заключается в создании продуктов. Обычно он содержит
53-
некоторую базовую бизнес-логику, которая основана на объектах Продуктов,
54-
возвращаемых фабричным методом. Подклассы могут косвенно изменять эту
55-
бизнес-логику, переопределяя фабричный метод и возвращая из него другой
56-
тип продукта.
53+
некоторую базовую бизнес-логику, которая основана на объектах
54+
Продуктов, возвращаемых фабричным методом. Подклассы могут косвенно
55+
изменять эту бизнес-логику, переопределяя фабричный метод и возвращая из
56+
него другой тип продукта.
5757
"""
5858

5959
# EN: Call the factory method to create a Product object.
@@ -145,7 +145,8 @@ def operation(self) -> str:
145145

146146

147147
def client_code(creator: Creator) -> None:
148-
print(f"Client: I'm not aware of the creator's class, but it still works.\n{creator.some_operation()}", end="")
148+
print(f"Client: I'm not aware of the creator's class, but it still works.\n"
149+
f"{creator.some_operation()}", end="")
149150

150151

151152
if __name__ == "__main__":

src/Flyweight/Structural/main.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,15 @@
1919

2020
class Flyweight():
2121
"""
22-
EN: The Flyweight stores a common portion of the state (also called intrinsic
23-
state) that belongs to multiple real business entities. The Flyweight accepts
24-
the rest of the state (extrinsic state, unique for each entity) via its
25-
method parameters.
22+
EN: The Flyweight stores a common portion of the state (also called
23+
intrinsic state) that belongs to multiple real business entities. The
24+
Flyweight accepts the rest of the state (extrinsic state, unique for each
25+
entity) via its method parameters.
2626
2727
RU: Легковес хранит общую часть состояния (также называемую внутренним
2828
состоянием), которая принадлежит нескольким реальным бизнес-объектам.
29-
Легковес принимает оставшуюся часть состояния (внешнее состояние, уникальное
30-
для каждого объекта) через его параметры метода.
29+
Легковес принимает оставшуюся часть состояния (внешнее состояние,
30+
уникальное для каждого объекта) через его параметры метода.
3131
"""
3232

3333
def __init__(self, shared_state: str) -> None:
@@ -48,8 +48,8 @@ class FlyweightFactory():
4848
4949
RU: Фабрика Легковесов создает объекты-Легковесы и управляет ими. Она
5050
обеспечивает правильное разделение легковесов. Когда клиент запрашивает
51-
легковес, фабрика либо возвращает существующий экземпляр, либо создает новый,
52-
если он ещё не существует.
51+
легковес, фабрика либо возвращает существующий экземпляр, либо создает
52+
новый, если он ещё не существует.
5353
"""
5454

5555
_flyweights: Dict[str, Flyweight] = {}

0 commit comments

Comments
 (0)