design-patterns
/
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
14In 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
16in Software development.
17These authors are collectively known as Gang of Four (GOF)
18
19As per the design pattern reference book `Design Patterns - Elements of Reusable Object-Oriented Software`, there
20are 23 design patterns which can be classified in three categories: Creational, Structural and Behavioral patterns.
21
22We'll also discuss another category of design pattern: J2EE design patterns.
23
24**Based on:**
25
26https://www.tutorialspoint.com/design_pattern/design_pattern_overview.htm<br/>
27https://ru.wikipedia.org/wiki/Design_Patterns
28
29### Creational patterns
30
31These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects
32directly using new operator. It gives program more flexibility in deciding which objects need to be created for a
33given use case.
34
35In [FACTORY](src/main/java/creational/factorymethod) pattern, we create object without exposing the creation logic to the client and refer to newly created
36object 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
39factory of factories.
40In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly
41specifying 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
47object gets created. This class provides a way to access its only object which can be accessed directly without need to
48instantiate 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
53independent 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
59implementing a prototype interface which tells to create a clone of the current object. The pattern is used when
60creation of object directly is costly. For example, an object is to be created after a costly database operation.
61We can cache the object, returns its clone on next request and update the database as and when needed thus reducing
62database calls.
63
64Паттерн создания объекта через клонирование другого объекта вместо создания через конструктор
65
66---
67
68### Structural Patterns
69
70These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and
71define 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
74structural pattern as this pattern combines the capability of two independent interfaces.
75This pattern involves a single class which is responsible to join functionalities of independent or incompatible
76interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a
77laptop. You plug in the memory card into card reader and card reader into the laptop so that memory card can be read via
78laptop.
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.
81This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract
82class by providing a bridge structure between them.
83This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent
84from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
85
86FILTER pattern or CRITERIA pattern is a design pattern that enables developers to filter a set of objects using
87different criteria and chaining them in a decoupled way through logical operations. This type of design pattern comes
88under 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
91pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This type of design
92pattern comes under structural pattern as this pattern creates a tree structure of group of objects.
93This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of
94same 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
97type of design pattern comes under structural pattern as this pattern acts as a WRAPPER to existing class.
98This pattern creates a decorator class which wraps the original class and provides additional functionality keeping
99class 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
102access the system. This type of design pattern comes under structural pattern as this pattern adds an interface to
103existing system to hide its complexities.
104This pattern involves a single class which provides simplified methods required by client and delegates calls to
105methods 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
108increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to
109decrease object count thus improving the object structure of application.
110Flyweight pattern tries to reuse already existing similar kind objects by storing them and creates new object when no
111matching object is found.
112
113In [PROXY](src/main/java/structural/proxy) pattern, a class represents functionality of another class.
114In proxy pattern, we create object having original object to interface its functionality to outer world.
115
116---
117
118### Behavioral Patterns
119
120These 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
123receiver of a request based on type of request.
124In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request
125then 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
128object. Invoker object looks for the appropriate object which can handle this command and passes the command to the
129corresponding object which executes the command.
130
131[INTERPRETER](src/main/java/behavioral/interpreter) pattern provides a way to evaluate language grammar or expression.
132This pattern involves implementing an expression interface which tells to interpret a particular context. This pattern
133is 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.
136This pattern is used to get a way to access the elements of a collection object in sequential manner without any need
137to know its underlying representation.
138
139[MEDIATOR](src/main/java/behavioral/mediator) pattern is used to reduce communication complexity between multiple objects or classes.
140This pattern provides a mediator class which normally handles all the communications between different classes and
141supports 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.
144Memento pattern uses three actor classes. Memento contains state of an object to be restored. Originator creates and
145stores 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
148dependent objects are to be notified automatically.
149Observer pattern uses three actor classes. Subject, Observer and Client. Subject is an object having methods to attach
150and detach observers to a client object.
151
152In [STATE](src/main/java/behavioral/state) pattern a class behavior changes based on its state.
153In State pattern, we create objects which represent various states and a context object whose behavior varies as its
154state object changes.
155
156In [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
157value, Null Object reflects a do nothing relationship. Such Null object can also be used to provide default behaviour
158in case data is not available.
159In Null Object pattern, we create an abstract class specifying various operations to be done, concrete classes
160extending this class and a null object class providing do nothing implementation of this class and will be used
161seamlessly where we need to check null value.
162
163In [STRATEGY](src/main/java/behavioral/strategy) pattern, a class behavior or its algorithm can be changed at run time.
164In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as
165per its strategy object. The strategy object changes the executing algorithm of the context object.
166
167In [TEMPLATE](src/main/java/behavioral/templatemethod) pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can
168override the method implementation as per need but the invocation is to be in the same way as defined by an abstract
169class.
170
171In [VISITOR](src/main/java/behavioral/visitor) pattern, we use a visitor class which changes the executing algorithm of an element class. By this way,
172execution algorithm of element can vary as and when visitor varies.
173As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the
174element object.
175Применяется в случаях, когда необходимо для ряда классов сделать похожую (одну и ту же) операцию.
176
177---
178
179### J2EE Patterns
180
181These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java
182Center.
183
184MVC 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
187changes.
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
190whenever data changes. It keeps view and model separate.
191
192BUSINESS DELEGATE pattern is used to decouple presentation tier and business tier. It is basically use to reduce
193communication or remote lookup functionality to business tier code in presentation tier code. In business tier we have
194the 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
199object access to business delegate object.
200* Business Service - Business Service interface. Concrete classes implement this business service to provide actual
201business implementation logic.
202
203COMPOSITE ENTITY pattern is used in EJB persistence mechanism. A Composite entity is an EJB entity bean which represents
204a graph of objects. When a composite entity is updated, internally dependent objects beans get updated automatically as
205being 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
208used for persistence purpose
209* Coarse-Grained Object - This object contains dependent objects. It has its own life cycle and also manages life cycle
210of 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
214DATA ACCESS OBJECT Pattern or DAO pattern is used to separate low level data accessing API or operations from high level
215business 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
219a 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
221class.
222
223FRONT CONTROLLER design pattern is used to provide a centralized request handling mechanism so that all requests will be
224handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and
225then 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
229handler
230* View - Views are the object for which the requests are made.
231
232INTERCEPTING FILTER design pattern is used when we want to do some pre-processing / post-processing with request or
233response of the application. Filters are defined and applied on the request before passing the request to actual target
234application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests
235to 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
243SERVICE LOCATOR design pattern is used when we want to locate various services using JNDI lookup. Considering high cost
244of looking up JNDI for a service, Service Locator pattern makes use of caching technique. For the first time a service
245is required, Service Locator looks up in JNDI and caches the service object. Further lookup or same service via Service
246Locator is done in its cache which improves the performance of application to great extent. Following are the entities
247of 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
255TRANSFER OBJECT pattern is used when we want to pass data with multiple attributes in one shot from client to server.
256Transfer object is also known as Value Object. Transfer Object is a simple POJO class having getter/setter methods and
257is serializable so that it can be transferred over the network. It does not have any behavior. Server Side business
258class normally fetches data from the database and fills the POJO and send it to the client or pass it by value. For
259client, transfer object is read-only. Client can create its own transfer object and pass it to server to update values
260in 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