0% found this document useful (0 votes)
18 views

DesignPatterns Java Mar2022

Uploaded by

puja vijayakumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

DesignPatterns Java Mar2022

Uploaded by

puja vijayakumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Design Patterns in JAVA

Design Patterns in Java


Agenda
• You will have functional knowledge of design patterns and the principles behind them

• Prerequisites: Beginner level of knowledge in Java and Object Oriented Programming


• Understanding design patterns
• Why are design pattern important?
• Getting to know
• Behavioral
• Creational
• Structural
• Exploring other design patterns in Java
• Audience
• Unfamiliar with design patterns – Beginner’s perspective
• Definitive Design Pattern Book
• Design Patterns: Elements of reusable Object-Oriented Software (1995)
Why to learn Design Patterns
• Design patterns represent design solutions which have been used across similar design problems and
have proved to be effective time and again

• Design Patterns give a common terminology to be used to discuss designs

• Design Patterns help thinking about designs at a pattern level without going in the low-level object
details E.g. using Observer Pattern tells us that there would be a subject class and an observer class and
the relationship between them without going into the details of the way they will be communicating with
each other
The Gang of Four
Important Aspects
OOPS Building Blocks
OOPs Principles – behind Design Patterns
• Decoupling: Strive for loosely coupled designs between objects that interact
• Open/Closed Principle: Classes should be open for extension but closed for modification (= classes
should be easy to extend without needing to change them).
• Abstraction(Programming to Interfaces): Depend on abstractions, do not depend on concrete classes
• Single Responsibility: A class should have only one reason to change.
• DRY (Don’t Repeat Yourself): Store information in a single place, do not scatter it throughout your
code
• Dependency Inversion: don’t ask, let framework give it to you
• Encapsulate what changes: hides implementation detail, help in maintenance
Description
• Patterns are discovered, not created
• A Reusable and named solution to a recurring problem in a context
• “Each pattern describes a problem which occurs over and over again
in our environment, and then describes the core of the solution to
that problem, in such a way that you can use this solution a million
times over, without ever doing it the same way twice.”
• Design patterns capture the best practices of experienced object-
oriented software developers.
• Design patterns are solutions to general software development
problems.
Design Pattern Types
• Erich Gamma, Richard Helm, Ralph Johnson and John Vlisides in their Design Patterns book define 23
design patterns divided into three types:

• Creational patterns are ones that create objects for you, rather than having you instantiate objects
directly. This gives your program more flexibility in deciding which objects need to be created for a
given case.

• Structural patterns help you compose groups of objects into larger structures, such as complex user
interfaces or accounting data.

• Behavioral patterns help you define the communication between objects in your system and how the
flow is controlled in a complex program.
Classification
Importance of Patterns
• Patterns capture expert knowledge
• Reuse the knowledge
• Find the appropriate design
• Shared and Precise vocabulary

• Inheritance is not always the best solution


• Composition can offer more flexible alternative
• Patterns can guide

• Study and know principle of patterns


Strategy Pattern
Builder Pattern
Builder Pattern
• The purpose of the builder pattern is to separate the construction of a complex object from its representation. so that the
same construction process can create different representation. An example of this is meals at a fast food restaurant. The
meal typically consists of a starter, main course, soft drink, desert and goodies. No matter whether you choose different
burgers/drinks, the construction of the kids meal follows the same process
Meal {
starter[]: max 2, min 0 // Fries, Boiled, Baked
main-course[]: max 1, min 1 // North, South, Chinese, Pizza
soft-drink[]: max 1, min 0 // FreshJuice, Carbonated, Shakes
desert: min 0 // FreshFruits, Pasteries, DryFruitNut, Sweets
goodies: min 1 // Artbook, StoryBook, Toys, Stationary
}
• This pattern is used when object creation algorithms should be decoupled from the system, and multiple representations of
creation algorithms are required. This decoupling is useful as you can add new creation functionality to your system without
affecting the core code. You also get control over the creation process at runtime with this approach
Builder Pattern
• Allows for object level access control by acting as a pass through entity or a placeholder object.

• The builder pattern is a creational design pattern used to assemble complex objects step by step . With the builder pattern,
the same object construction process can be used to create different objects

Implementation
• The Builder class specifies an abstract interface for creating parts of a Product object.
• The ConcreteBuilder constructs and puts together parts of the product by implementing the Builder interface. It defines and
keeps track of the representation it creates and provides an interface for saving the product.
• The Director class constructs the complex object using the Builder interface.
• The Product represents the complex object that is being built.
The builder pattern will typically use other creational patterns to get products built (e.g. Prototype or Singleton) and will often
build a composite
Bridge Pattern
Builder Pattern
• Decoupling abstraction from implementation - Inheritance tightly couples an abstraction with an implementation at compile
time. Bridge pattern can be used to avoid the binding between abstraction and implementation and to select the
implementation at run time.
• Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy.
• Beyond encapsulation, to insulation
• Decoupling interface from implementation and hiding implementation detail of abstraction from client is main objectives of
bridge design pattern.
Builder Pattern
• Sometimes an abstraction should have different implementations; consider an object that handles persistence of
objects over different platforms using either relational databases or file system structures (files and folders). A simple
implementation might choose to extend the object itself to implement the functionality for both file system and
RDBMS. However this implementation would create a problem; Inheritance binds an implementation to the
abstraction and thus it would be difficult to modify, extend, and reuse abstraction and implementation
independently
• The Bridge pattern should be used when both the class as well as what it does vary often. The bridge pattern can also
be thought of as two layers of abstraction. When the abstractions and implementations should not be bound at
compile time, and should be independently extensible the pattern should be used
Builder Pattern
Implementation
The Abstraction defines the abstraction, and maintains the reference to the implementor.
RefinedAbstraction provides an extension to the Abstraction, usually adding extra methods that provide
different ways of getting at the same functionality.
The Implementor interface defines an interface for the implementation classes (the ConcreateImplementor
classes).
RefinedAbstractions are implemented in terms of the abstraction, and not that implementation interface. his
means that the implementation details are hidden from the client.
The pattern is similar to the Adapter pattern, except the Bridge pattern separates the interface from
implementation
Objects need to be created on demand.
Access control for the original object is required
Added functionality is required when an object is accessed
Builder Pattern
Observer Pattern
Observer Pattern

▪ This pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependants
are notified and updated
Observer Pattern in JAVA
• PropertyChangeListener in JavaBeans
• add/remove listener methods in AbstractButton
• Listeners in Servletss
add/remove listener methods Listeners in Servlets
Motivation

• You want to use this pattern to reduce coupling. If you have an object that needs to share its state with others, without
knowing who those objects are, the Observer is exactly what you need.

• You'll have seen, and probably used, the Observer many times if you've done any UI programming, especially in Swing. The
whole concept of listeners is based on this pattern. The event listener is the most popular, where you register an
ActionListener to a UI control, such a button, and react to action events using the actionPerformed method. In this case, the
ActionListener is the Observer and the button is your Subject. As the button changes state, you can react, if you choose to, in
your actionPerformed method
Implementation
Implementation

• Subject - interface or abstract class defining the operations for attaching and de-attaching observers to the client
• Concrete Subject - concrete Subject class. It maintains the state of the object and when a change in the state occurs it notifies
the attached Observers.
• Observer - interface or abstract class defining the operations to be used to notify this object.
• ConcreteObserver - concrete Observer implementations.
Example

Java.util.Observer and java.util.Observable

The slight difference from the classic definition is that Observable is


used in place of the Subject and is implemented as a class with
most of the methods as protected, while the Observer interface
remains the same.
Example

Let us take a blog and subscriber example for observer design pattern sample implementation.

public interface Subject { public void unRegisterObserver(Observer observer) {


public void registerObserver(Observer observer); observersList.remove(observer);
public void notifyObserver(); }
public void unRegisterObserver(Observer observer); public void notifyObserver() {
public Object getUpdate(); if (stateChange) {
} for (Observer observer : observersList) {
observer.update();
public class Blog implements Subject { }
}
List<Observer> observersList; }
private boolean stateChange;
public Object getUpdate() {
public Blog() { Object changedState = null;
this.observersList = new ArrayList<Observer>(); if (stateChange) {
stateChange = false; changedState = "Observer Design Pattern";
} }
return changedState;
public void registerObserver(Observer observer) { }
observersList.add(observer);
} public void postNewArticle() {
stateChange = true;
notifyObserver();
}
Example

Let us take a blog and subscriber example for observer design pattern sample implementation.

public interface Observer { public String getArticle() {


public void update(); return article;
public void setSubject(Subject subject); }
} }

public class User implements Observer { public class ObserverDesignPattern {


private String article; public static void main(String args[]) {
private Subject blog; Blog blog = new Blog();
User user1 = new User();
public void setSubject(Subject blog) { User user2 = new User();
this.blog = blog; blog.registerObserver(user1);
article = "No New Article!"; blog.registerObserver(user2);
} user1.setSubject(blog);
@Override user2.setSubject(blog);
public void update() {
System.out.println("State change System.out.println(user1.getArticle());
reported by Subject."); blog.postNewArticle();
article = (String) blog.getUpdate(); System.out.println(user1.getArticle());
} }
}
Other Patterns
• Enterprise development
• Data persistence, Concurrency, Third-party integration
• MVC architectural Pattern - Separation of concerns –
Composite(View), Strategy (View2Controller) Obserserver
(Notify)

• Functional Programming
• High order functions, Pure functions
• Java not a functional programming language
• MapReuce (Break and aggregate), Memoization (cache),
Monad (Container type)

• Reactive Programming
• Event-driven, Data flow,
• Non-blocking, Asynchronous, Declarative
• Observer and Iterator patterns
• Producer and Consumer through a subscription

You might also like