Mastering Design Patterns in Java _ by Dharshi Balasubramaniyam _ Javarevisited _ Feb, 2024 _ Medium
Mastering Design Patterns in Java _ by Dharshi Balasubramaniyam _ Javarevisited _ Feb, 2024 _ Medium
268 6
In the world of software engineering, turning ideas into actual code can be
tricky.
00 : 00 : 4 1
Get Premium
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 1/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
In this article, we’ll delve into some of the most important design patterns
that every developer should be familiar with. We’ll explore their principles,
why they’re useful, and how you can use them in real projects. Whether
you’re struggling with creating objects, organizing relationships between
classes, or managing how objects behave, there’s a design pattern that can
help.
Let’s begin.
1. Singleton pattern
The Singleton pattern is a creational design pattern that ensures a class has
only one instance and provides a global point of access to that instance. In
simpler terms, it’s like ensuring there’s only one unique copy of a particular
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 2/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
object in your program, and you can access that object from anywhere in
your code.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 3/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
clipboard1.copy("Java");
clipboard2.copy("Design patterns");
Clearly, this isn’t ideal. We expect both clipboard instances to display the
same value. This is precisely where the Singleton pattern proves its worth.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 4/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
clipboard1.copy("Java");
clipboard2.copy("Design patterns");
Now, both clipboard1 and clipboard2 reference the same instance of the
Clipboard class, ensuring consistency across the application.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 5/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
The challenge is you need a way to create these operation objects without
making your code too complex or tightly coupled. This means you don’t want
your code to rely too heavily on the specific classes of operations directly.
You also want to make it easy to add new types of operations later without
changing a lot of code.
The Factory Design Pattern helps you solve this problem by providing a way
to create objects without specifying their exact class. Instead, you delegate
the creation process to a factory class.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 6/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
// for addition
public class AddOperation implements Operation{
@Override
public double calculate(double number1, double number2) {
return number1 + number2;
}
}
// for substration
public class SubOperation implements Operation{
@Override
public double calculate(double number1, double number2) {
return number1 - number2;
}
}
// for multiplication
public class MulOperation implements Operation{
@Override
public double calculate(double number1, double number2) {
return number1 * number2;
}
}
// for division
public class DivOperation implements Operation{
@Override
public double calculate(double number1, double number2) {
if(number2 == 0)
throw new ArithmeticException("Cannot divide by zero!");
return number1 / number2;
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 7/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
// An exception class invokes when user input invalid choice for operation
public class InvalidOperationException extends Exception{
public InvalidOperationException(String message) {
super(message);
}
4. Use the factory to create objects without knowing their specific classes.
try {
// printing result
System.out.println("\nThis result is " + operation.calculate(operand1, operan
}
catch (InputMismatchException e) {
System.out.println("Invalid input type!\n");
}
catch (InvalidOperation | ArithmeticException e) {
System.out.println(e.getMessage());
}
scan.close();
}
Here the Main class demonstrates the usage of the factory to create different
operation objects without knowing their specific implementation classes
(Loose coupling). It only interacts with the factory interface. Not only that,
but we can also easily add new types of operations without changing existing
client code. We are just needed to create a new concrete product and update
the factory if necessary.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 9/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
3. Builder pattern
the Builder Pattern provides a way to construct an object by allowing you to
set its various properties (or attributes) in a step-by-step manner.
Some of the parameters might be optional for an object, but we are forced to
send all the parameters and optional parameters need to send as NULL. We
can solve this issue with large number of parameters by providing a
constructor with required parameters and then different setter methods to
set the optional parameters.
This pattern is particularly useful when dealing with objects that have many
optional parameters or configurations.
Imagine we’re developing a user entity. Users have different properties like
name, email, phone and city etc. Here name and email are required fields
and phone and city are optional. Now, each person might have different
combinations of these properties. Some might have city, others might not.
Some might have phone, others might not. The Builder Design Pattern helps
you create these users flexibly, step by step.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 10/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
@Override
public String toString() {
return "User = " +
"{ name: '" + name + '\'' +
", email: '" + email + '\'' +
", phone: '" + phone + '\'' +
", city: '" + city + '\'' +
" }";
}
// builder class
public static class UserBuilder {
private String name; // required field
private String email; // required field
private String phone = "unknown"; // optional field
private String city = "unknown"; // optional field
// getters
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 11/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
User class: Is the class represents the product you want to build using the
builder pattern. It has private fields to represent the properties of the
user ( name , email , phone , city ). The constructor of User takes a
UserBuilder object and initializes its fields based on the builder's settings.
There is a static method builder() that returns a new instance of
UserBuilder , providing a convenient way to create a new builder.
Here’s an example of how you can use this code to create a user with
optional properties:
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 12/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
.build();
So that’s what builder patterns is guys. This pattern is useful when you have
complex objects with many optional parameters, and it helps keep your code
clean and easy to understand. It allows you to construct different variations
of objects with the same builder, adjusting parameters as needed.
4. Adapter pattern
The Adapter pattern is a structural design pattern that allows objects with
incompatible interfaces to work together. It acts as a bridge between two
incompatible interfaces.
Adapter is the class that implements the Target interface and wraps the
Adaptee class.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 13/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
Client class is the class that uses the adapter to interact with the Adaptee
through the Tareget interface.
// Target interface
interface CellPhone {
void call();
}
@Override
public void call() {
friendCellPhone.ring();
}
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 14/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
// Client class
public class AdapterMain {
public static void main(String[] args) {
// Using the adapter to make Adaptee work with Target interface
FriendCellPhone adaptee = new FriendCellPhone();
CellPhone adapter = new CellPhoneAdapter(adaptee);
adapter.call();
}
}
In this example:
CellPhone is the target interface that your client code expects, and you do
not have an implementation of it.
class.
AdapterMain class serves as the client that demonstrates the usage of the
Adapter pattern in action.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 15/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
The client might only require specific functionality from the Adaptee. By
using an adapter, you can provide a tailored interface that exposes only
the necessary functionality, rather than exposing the entire interface of
the Adaptee.
5. Decorator pattern
The Decorator Pattern is a design pattern in object-oriented programming
that allows behavior to be added to individual objects, either statically or
dynamically, without affecting the behavior of other objects from the same
class.
In this pattern, there is a base class (or interface) that defines the common
functionality, and one or more decorator classes that add additional
behavior. These decorator classes wrap the original object, augmenting its
behavior in a modular and flexible way.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 16/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
Imagine, you are tasked with creating a drawing application that allows users
to create and customize shapes with various decorations. It should be able to
easily add new decorators for additional features without changing the
existing code for shapes or other decorators.
// Shape Interface
interface Shape {
void draw();
String getName();
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 17/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
@Override
public void draw() {
System.out.println("Drawing circle, " + getName() + ".");
}
}
Shape Interface: Defines the basic operations that all shapes should
support. In this case, it includes the draw() method to draw the shape
and getName() to get the name of the shape.
@Override
public void draw() {
decoratedShape.draw();
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 18/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
@Override
public String getName() {
return decoratedShape.getName();
}
}
@Override
public void draw() {
super.draw();
System.out.println("Adding " + widthInPxs + "px, " + color + " color bor
}
}
@Override
public void draw() {
super.draw();
System.out.println("Filling with " + color + " color to " + getName() +
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 19/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
}
}
// Main Class
public class DecoratorMain {
public static void main(String[] args) {
// Create a circle
Shape circle1 = new Circle("circle1");
// output
// Drawing circle, circle1.
// Adding 2px, red color border to circle1.
// Filling with blue color to circle1.
}
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 20/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
and then further decorates it with a color. Finally, it calls the draw()
6. Observer pattern
The Observer Pattern a behavioral design pattern commonly used in object-
oriented programming to establish a one-to-many dependency between
objects. In this pattern, one object (called the subject or observable)
maintains a list of its dependents (observers) and notifies them of any state
changes, usually by calling one of their methods.
Subject: This is the object that holds the state and manages the list of
observers. It provides methods to attach, detach, and notify observers.
Observer: This is the interface that defines the method(s) that the subject
calls to notify the observer of any state changes. Typically, observers
implement this interface.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 21/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 22/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
@Override
public String toString() {
return eventType.name() + " on " + topic;
}
}
EventType: The EventType enum defines the types of events that can
occur, such as NEW_VIDEO , LIVE_STREAM and more.
Event: The YoutubeEvent class represents the events that occur in the
system. It contains information such as the type of event and the topic.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 23/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
package observer;
import java.util.ArrayList;
import java.util.List;
@Override
public void addSubscriber(Observer observer) {
subscribers.add(observer);
}
@Override
public void removeSubscriber(Observer observer) {
subscribers.remove(observer);
}
@Override
public void notifyAllSubscribers(YoutubeEvent event) {
for(Observer observer: subscribers) {
observer.notifyMe(getName(), event);
}
}
}
event occurs.
package observer;
@Override
public void notifyMe(String youtubeChannelName, YoutubeEvent event) {
System.out.println("Dear " + getName() + ", Notification from " + youtub
}
}
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 25/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
myChannel.addSubscriber(john);
myChannel.addSubscriber(bob);
myChannel.addSubscriber(tom);
}
}
Main Class: The ObserverMain class contains the main method where we
test our implementation. It creates a YoutubeChannel instance, adds
subscribers to it, notifies them of new video event, and removes one of
the subscribers and again notifies them of a live stream event.
// output
Dear John, Notification from MyChannel: NEW_VIDEO on Design patterns
Dear Bob, Notification from MyChannel: NEW_VIDEO on Design patterns
Dear Tom, Notification from MyChannel: NEW_VIDEO on Design patterns
By using the Observer design pattern, the YouTube channel can easily notify
all its subscribers whenever a new video is uploaded without tightly coupling
the channel and its subscribers. This promotes a more flexible and
maintainable design.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 26/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
So guys, we have reached the end of this article, Thank you for taking the
time to read this article! I hope you found the information helpful and
gained some valuable insights into the topic. From understanding what
design patterns are to exploring real-world examples of design patterns,
we’ve covered a lot.
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 27/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
Generics in JAVA
If you found my articles useful, please consider giving it claps and sharing it
with your friends and colleagues.
Happy coding!
-Dharshi Balasubramaniyam-
163 350 6
605 9 31
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 29/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
163 199 1
Lists
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 30/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
When to use GraphQL, gRPC, and The guide to Git I never had.
REST? 🩺 Doctors have stethoscopes.
Building APIs is one of the most important
tasks for developers in modern engineering.…
636 4 3.1K 25
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 31/32
4/25/24, 2:34 PM Mastering Design Patterns in Java | by Dharshi Balasubramaniyam | Javarevisited | Feb, 2024 | Medium
169 4 18
https://medium.com/javarevisited/mastering-design-patterns-in-java-1e39194ac480 32/32