Java
Design Patterns
Learn essential design patterns: Singleton, Factory, Observer, and more.
By TechCoder TeamLast updated: 2026-06-02
In a Nutshell
Learn essential design patterns: Singleton, Factory, Observer, and more. This hands-on tutorial focuses on practical implementation of design patterns concepts.
Design Patterns
Design Patterns are reusable solutions to common software design problems.
Creational Patterns
Singleton
Ensures only one instance of a class exists.
class Database {
private static Database instance;
private Database() {} // Private constructor
public static Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
}
Factory
Creates objects without specifying the exact class.
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() { System.out.println("Circle"); }
}
class Square implements Shape {
public void draw() { System.out.println("Square"); }
}
class ShapeFactory {
public Shape getShape(String type) {
if (type.equals("CIRCLE")) return new Circle();
if (type.equals("SQUARE")) return new Square();
return null;
}
}
Structural Patterns
Adapter
Converts one interface to another.
interface MediaPlayer {
void play(String file);
}
class MP3Player implements MediaPlayer {
public void play(String file) {
System.out.println("Playing MP3: " + file);
}
}
class MP4Player {
public void playMP4(String file) {
System.out.println("Playing MP4: " + file);
}
}
class MediaAdapter implements MediaPlayer {
MP4Player mp4Player = new MP4Player();
public void play(String file) {
mp4Player.playMP4(file);
}
}
Behavioral Patterns
Observer
Notifies multiple objects about state changes.
interface Observer {
void update(String message);
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void attach(Observer observer) {
observers.add(observer);
}
public void notifyAllObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}
Strategy
Defines a family of algorithms and makes them interchangeable.
interface PaymentStrategy {
void pay(int amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card");
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal");
}
}
class ShoppingCart {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(int amount) {
paymentStrategy.pay(amount);
}
}
AI Mentor
Confused about "Common Java design patterns and their implementations"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What does Singleton pattern ensure?
Only one instance exists
Multiple instances
No instances