Adapter Pattern
Adapter Pattern
Singleton pattern only allows creation of only one object from a class. It
won’t create any new object even if it is frequently called using the new
keyword, it only returns the single object that was created.
For example:
Dhoro ekta boro office e ekjon Boss ache j shob team er upor control
rakhe.
Ekhon prottek team jodi nijer nijer boss niye ney tahole office e juddho
lagbe!
Code:
class Logger {
System.out.println("Logger Initialized.");
if (instance == null) {
return instance;
}
}
Singleton Design Pattern is applied here to make sure that the Logger object
is created only once and shared across the whole application. This avoids
inconsistency and ensures centralized control over logging.
Factory Pattern:
Imagine you own a vehicle factory. Customer visits and asks for different
types of vehicle like, ‘car’, ‘truck’, ‘bike’, etc. Now when you send a request
to the factory for manufacture, you only say the type of vehicle and the
factory prepares it for you.
Q: You are designing a vehicle rental system where users can
request different types of vehicles like Car and Bike.
Use the Factory Design Pattern to implement the following:
A Vehicle interface
A driver class that takes user input and shows the vehicle output.
// Step 1: Interface
interface Vehicle {
void start();
System.out.println("Car started!");
System.out.println("Bike started!");
class VehicleFactory {
if (type.equalsIgnoreCase("Car")) {
} else if (type.equalsIgnoreCase("Bike")) {
} else {
return null;
Vehicle v1 = VehicleFactory.getVehicle("Car");
v1.start();
Vehicle v2 = VehicleFactory.getVehicle("Bike");
v2.start();
Builder Pattern:
Builder Pattern is used when a complex object is built step by step.
For example:
Dhoro customer chailo, “Amake burger dao, lettuce diba, sauce diba,
cheese diba.”
.addCheese()
.addLettuce()
.addSauce()
.build();
Q: You are building a meal-ordering system. A meal may have
optional items such as drink, dessert, salad, and main course.
Implement this using the Builder Pattern so that:
class Meal {
this.drink = builder.drink;
this.dessert = builder.dessert;
this.salad = builder.salad;
this.mainCourse = builder.mainCourse;
System.out.println("Meal includes:");
// Builder Class
this.drink = true;
return this;
this.dessert = true;
return this;
this.salad = true;
return this;
this.mainCourse = true;
return this;
}
}
.addDrink()
.addMainCourse()
.addDessert()
.build();
myMeal.showItems();
Example imagine client asked for sofa, table, and a chair, and tells that the
design has to be modern and wants Victorian design chair.
Now you know all those have to be of the same design and if chair Victorian,
sofa is as well, and there is no mismatch.
Therefore:
// Abstract Products
interface Chair {
void sitOn();
interface Sofa {
void lieOn();
}
// Concrete Products - Modern
// Abstract Factory
interface FurnitureFactory {
Chair createChair();
Sofa createSofa();
// Concrete Factories
chair.sitOn();
sofa.lieOn();
factory.createChair().sitOn();
factory.createSofa().lieOn();
- In this code we have use different design variant for Chair and Sofa.
Abstract Factory (FurnitureFactory) can help us create a full set design
of the same family (Modern and Victorian).
Adapter Pattern:
Adapter Pattern is used when the interface of two systems don’t match and
we use ‘adapter’ to match them.
Example:
- Imagine tomar kaache 3 pin plug ache but tomar room e 2 pin er
socket. Therefore tomar ekta adapter dorkar jeta 3 pin k 2 pin e
convert kore dey.
Q: You have a legacy OldSystem class with a method fetchOldData().
But the client expects to call a method fetchData().
Use Adapter Pattern so that the new system can interact with the
old one without changing its code.
Implement with:
// Old/Legacy class
class OldSystem {
interface DataFetcher {
void fetchData();
// Adapter class
this.oldSystem = oldSystem;
Decorator Pattern:
We use decorator pattern when we want to add new features without
modifying the original class.
Example:
Dhoro tumi ekta pizza shop chalao, customer ke plain pizza dao. Kintu ekhon
customer bole:
“Cheese lagbe”
“Mushroom lagbe”
“Pepperoni o lagbe”
Ekhon tumi plainPizza class k manage na kore tumi Decorator diye bolcho:
The base pizza class represents a simple pizza with a default cost
interface Pizza {
String getDescription();
double getCost();
return 5.0;
// Abstract Decorator
this.pizza = pizza;
// Cheese Topping
super(pizza);
}
public String getDescription() {
// Mushroom Topping
super(pizza);
// Pepperoni Topping
super(pizza);
// Step-by-step build
Strategy Pattern:
We use strategy pattern when we want to change an objects behavior or
algorithm during runtime.
For example:
Dhoro tumi ekta travel app banaccho. User bole, “Ami University jabo but bus
e, ba train-e, ba uber-e jabo.
// Strategy Interface
interface TravelStrategy {
void travel();
// Concrete Strategies
System.out.println("Traveling by Bus...");
System.out.println("Traveling by Uber...");
System.out.println("Traveling by Train...");
// Context Class
class Traveler {
this.strategy = strategy;
strategy.travel();
}
}
person.setStrategy(new BusStrategy());
person.startTravel();
person.setStrategy(new UberStrategy());
person.startTravel();
person.setStrategy(new TrainStrategy());
person.startTravel();
Observer Pattern:
Observer Pattern is used when you want to notify many other objects when
there is a change in the main object.
Example;
Dhoro tumi ekta youtube channel chalao and onno manush tomake subscribe
kore. Everytime tumi new video upload koro tomar subscribers ra notification
pay. Ekhane YouTube channel hocche subject r subscribers ra hocche
observers. And j subscribers der notify kora hocche sheta observer pattern.
// Observer Interface
interface Observer {
// Subject Interface
interface Subject {
void notifyObservers();
// Concrete Subject
this.observer1 = o;
this.observer2 = o;
}
public void notifyObservers() {
if (observer1 != null) {
observer1.update(latestNews);
if (observer2 != null) {
observer2.update(latestNews);
this.latestNews = news;
notifyObservers();
// Concrete Observer
this.name = name;
}
public class Main {
agency.subscribe1(reader1);
agency.subscribe2(reader2);
agency.newArticle("Big Breaking!");