design-patterns

Форк
0
/
README.MD 
263 строки · 18.2 Кб
1

2
# Design patterns
3

4
![Java CI with Maven](https://github.com/andrei-punko/design-patterns/workflows/Java%20CI%20with%20Maven/badge.svg)
5
[![Coverage](.github/badges/jacoco.svg)](https://github.com/andrei-punko/design-patterns/actions/workflows/maven.yml)
6
[![Branches](.github/badges/branches.svg)](https://github.com/andrei-punko/design-patterns/actions/workflows/maven.yml)
7

8
---
9
### Prerequisites:
10
- Maven 3
11
- JDK 21
12
---
13

14
In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled 
15
`Design Patterns - Elements of Reusable Object-Oriented Software` which initiated the concept of Design Pattern 
16
in Software development.
17
These authors are collectively known as Gang of Four (GOF)
18

19
As per the design pattern reference book `Design Patterns - Elements of Reusable Object-Oriented Software`, there 
20
are 23 design patterns which can be classified in three categories: Creational, Structural and Behavioral patterns.
21

22
We'll also discuss another category of design pattern: J2EE design patterns.
23

24
**Based on:**
25

26
https://www.tutorialspoint.com/design_pattern/design_pattern_overview.htm<br/>
27
https://ru.wikipedia.org/wiki/Design_Patterns
28

29
### Creational patterns
30

31
These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects
32
directly using new operator. It gives program more flexibility in deciding which objects need to be created for a 
33
given use case.
34

35
In [FACTORY](src/main/java/creational/factorymethod) pattern, we create object without exposing the creation logic to the client and refer to newly created 
36
object using a common interface.
37

38
[ABSTRACT FACTORY](src/main/java/creational/abstractfactory) patterns work around a super-factory which creates other factories. This factory is also called as 
39
factory of factories.
40
In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly 
41
specifying their classes. Each generated factory can give the objects as per the Factory pattern.
42

43
Предоставляет интерфейс для создания семейств взаимосвязанных или взаимозависимых объектов, не специфицируя их 
44
конкретных классов.
45

46
[SINGLETON](src/main/java/creational/singleton) pattern involves a single class which is responsible to create an object while making sure that only single 
47
object gets created. This class provides a way to access its only object which can be accessed directly without need to 
48
instantiate the object of the class.
49

50
Контролируемый доступ к единственному экземпляру
51

52
[BUILDER](src/main/java/creational/builder) pattern builds a complex object using simple objects and using a step-by-step approach. This builder is 
53
independent of other objects.
54

55
Отделяет конструирование сложного объекта от его представления, так что в результате одного и того же процесса 
56
конструирования могут получаться разные представления.
57

58
[PROTOTYPE](src/main/java/creational/prototype) pattern refers to creating duplicate object while keeping performance in mind. This pattern involves 
59
implementing a prototype interface which tells to create a clone of the current object. The pattern is used when 
60
creation of object directly is costly. For example, an object is to be created after a costly database operation. 
61
We can cache the object, returns its clone on next request and update the database as and when needed thus reducing 
62
database calls.
63

64
Паттерн создания объекта через клонирование другого объекта вместо создания через конструктор
65

66
---
67

68
### Structural Patterns
69

70
These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and 
71
define ways to compose objects to obtain new functionalities.
72

73
[ADAPTER](src/main/java/structural/adapter) pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under 
74
structural pattern as this pattern combines the capability of two independent interfaces.
75
This pattern involves a single class which is responsible to join functionalities of independent or incompatible 
76
interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a 
77
laptop. You plug in the memory card into card reader and card reader into the laptop so that memory card can be read via 
78
laptop.
79

80
[BRIDGE](src/main/java/structural/bridge) is used when we need to decouple an abstraction from its implementation so that the two can vary independently.
81
This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract 
82
class by providing a bridge structure between them.
83
This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent 
84
from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
85

86
FILTER pattern or CRITERIA pattern is a design pattern that enables developers to filter a set of objects using 
87
different criteria and chaining them in a decoupled way through logical operations. This type of design pattern comes 
88
under structural pattern as this pattern combines multiple criteria to obtain single criteria.
89

90
[COMPOSITE](src/main/java/structural/composite) pattern is used where we need to treat a group of objects in similar way as a single object. Composite 
91
pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design 
92
pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
93
This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of 
94
same objects.
95

96
[DECORATOR](src/main/java/structural/decorator) pattern allows a user to add new functionality to an existing object without altering its structure. This 
97
type of design pattern comes under structural pattern as this pattern acts as a WRAPPER to existing class.
98
This pattern creates a decorator class which wraps the original class and provides additional functionality keeping 
99
class methods signature intact.
100

101
[FACADE](src/main/java/structural/facade) pattern hides the complexities of the system and provides an interface to the client using which the client can 
102
access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to 
103
existing system to hide its complexities.
104
This pattern involves a single class which provides simplified methods required by client and delegates calls to 
105
methods of existing system classes.
106

107
[FLYWEIGHT](src/main/java/structural/flyweight) pattern is primarily used to reduce the number of objects created and to decrease memory footprint and 
108
increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to 
109
decrease object count thus improving the object structure of application.
110
Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no 
111
matching object is found.
112

113
In [PROXY](src/main/java/structural/proxy) pattern, a class represents functionality of another class.
114
In proxy pattern, we create object having original object to interface its functionality to outer world.
115

116
---
117

118
### Behavioral Patterns
119

120
These design patterns are specifically concerned with communication between objects.
121

122
[CHAIN OF RESPONSIBILITY](src/main/java/behavioral/chainofresponsibility) pattern creates a chain of receiver objects for a request. This pattern decouples sender and 
123
receiver of a request based on type of request.
124
In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request 
125
then it passes the same to the next receiver and so on.
126

127
[COMMAND](src/main/java/behavioral/command) pattern is a data driven design pattern. A request is wrapped under an object as command and passed to invoker 
128
object. Invoker object looks for the appropriate object which can handle this command and passes the command to the 
129
corresponding object which executes the command.
130

131
[INTERPRETER](src/main/java/behavioral/interpreter) pattern provides a way to evaluate language grammar or expression.
132
This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern 
133
is used in SQL parsing, symbol processing engine etc.
134

135
[ITERATOR](src/main/java/behavioral/iterator) pattern is very commonly used design pattern in Java.
136
This pattern is used to get a way to access the elements of a collection object in sequential manner without any need 
137
to know its underlying representation.
138

139
[MEDIATOR](src/main/java/behavioral/mediator) pattern is used to reduce communication complexity between multiple objects or classes.
140
This pattern provides a mediator class which normally handles all the communications between different classes and 
141
supports easy maintenance of the code by loose coupling.
142

143
[MEMENTO](src/main/java/behavioral/memento) pattern is used to restore state of an object to a previous state.
144
Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates and 
145
stores states in Memento objects and Caretaker object is responsible to restore object state from Memento.
146

147
[OBSERVER](src/main/java/behavioral/observer) pattern is used when there is one-to-many relationship between objects such as if one object is modified, its 
148
dependent objects are to be notified automatically.
149
Observer pattern uses three actor classes. Subject, Observer and Client. Subject is an object having methods to attach 
150
and detach observers to a client object.
151

152
In [STATE](src/main/java/behavioral/state) pattern a class behavior changes based on its state.
153
In State pattern, we create objects which represent various states and a context object whose behavior varies as its 
154
state object changes.
155

156
In [NULL OBJECT](src/main/java/behavioral/nullobject) pattern, a null object replaces check of NULL object instance. Instead of putting if check for a null 
157
value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour 
158
in case data is not available.
159
In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes 
160
extending this class and a null object class providing do nothing implementation of this class and will be used 
161
seamlessly where we need to check null value.
162

163
In [STRATEGY](src/main/java/behavioral/strategy) pattern, a class behavior or its algorithm can be changed at run time.
164
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as 
165
per its strategy object. The strategy object changes the executing algorithm of the context object.
166

167
In [TEMPLATE](src/main/java/behavioral/templatemethod) pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can 
168
override the method implementation as per need but the invocation is to be in the same way as defined by an abstract 
169
class.
170

171
In [VISITOR](src/main/java/behavioral/visitor) pattern, we use a visitor class which changes the executing algorithm of an element class. By this way, 
172
execution algorithm of element can vary as and when visitor varies.
173
As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the 
174
element object.
175
Применяется в случаях, когда необходимо для ряда классов сделать похожую (одну и ту же) операцию.
176

177
---
178

179
### J2EE Patterns
180

181
These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java 
182
Center.
183

184
MVC pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
185

186
* Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data 
187
changes.
188
* View - View represents the visualization of the data that model contains.
189
* Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view 
190
whenever data changes. It keeps view and model separate.
191

192
BUSINESS DELEGATE pattern is used to decouple presentation tier and business tier. It is basically use to reduce 
193
communication or remote lookup functionality to business tier code in presentation tier code. In business tier we have 
194
the following entities:
195

196
* Client - Presentation tier code may be JSP, servlet or UI java code.
197
* Business Delegate - A single entry point class for client entities to provide access to Business Service methods.
198
* LookUp Service - Lookup service object is responsible to get relative business implementation and provide business 
199
object access to business delegate object.
200
* Business Service - Business Service interface. Concrete classes implement this business service to provide actual 
201
business implementation logic.
202

203
COMPOSITE ENTITY pattern is used in EJB persistence mechanism. A Composite entity is an EJB entity bean which represents 
204
a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as 
205
being managed by EJB entity bean. Following are the participants in Composite Entity Bean:
206

207
* Composite Entity - It is primary entity bean. It can be coarse grained or can contain a coarse grained object to be 
208
used for persistence purpose
209
* Coarse-Grained Object - This object contains dependent objects. It has its own life cycle and also manages life cycle 
210
of dependent objects
211
* Dependent Object - Dependent object is an object which depends on coarse grained object for its persistence lifecycle
212
* Strategies - Strategies represents how to implement a Composite Entity
213

214
DATA ACCESS OBJECT Pattern or DAO pattern is used to separate low level data accessing API or operations from high level 
215
business services. Following are the participants in Data Access Object Pattern.
216

217
* Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).
218
* Data Access Object concrete class - This class implements above interface. This class is responsible to get data from 
219
a data source which can be database / xml or any other storage mechanism.
220
* Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO 
221
class.
222

223
FRONT CONTROLLER design pattern is used to provide a centralized request handling mechanism so that all requests will be 
224
handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and 
225
then pass the requests to corresponding handlers. Following are the entities of this type of design pattern:
226

227
* Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based)
228
* Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific 
229
handler
230
* View - Views are the object for which the requests are made.
231

232
INTERCEPTING FILTER design pattern is used when we want to do some pre-processing / post-processing with request or 
233
response of the application. Filters are defined and applied on the request before passing the request to actual target 
234
application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests 
235
to corresponding handlers. Following are the entities of this type of design pattern:
236

237
* Filter - Filter which will performs certain task prior or after execution of request by request handler
238
* Filter Chain - Filter Chain carries multiple filters and help to execute them in defined order on target
239
* Target - Target object is the request handler
240
* Filter Manager - Filter Manager manages the filters and Filter Chain
241
* Client - Client is the object who sends request to the Target object
242

243
SERVICE LOCATOR design pattern is used when we want to locate various services using JNDI lookup. Considering high cost 
244
of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service 
245
is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service 
246
Locator is done in its cache which improves the performance of application to great extent. Following are the entities 
247
of this type of design pattern.
248

249
* Service - Actual Service which will process the request. Reference of such service is to be looked upon in JNDI server
250
* Context / Initial Context - JNDI Context carries the reference to service used for lookup purpose
251
* Service Locator - Service Locator is a single point of contact to get services by JNDI lookup caching the services
252
* Cache - Cache to store references of services to reuse them
253
* Client - Client is the object that invokes the services via ServiceLocator
254

255
TRANSFER OBJECT pattern is used when we want to pass data with multiple attributes in one shot from client to server. 
256
Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and 
257
is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business 
258
class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For 
259
client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values 
260
in database in one shot. Following are the entities of this type of design pattern:
261

262
* Business Object - Business Service fills the Transfer Object with data
263
* Transfer Object - Simple POJO having methods to set/get attributes only
264
* Client - Client either requests or sends the Transfer Object to Business Object
265

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.