Strategy, Observer, Decorator

Strategy, Observer, Decorator

In the Java programming language, the Strategy Pattern, Observer Pattern, and Decorator Pattern are behavioral/structural class design pattern methods. The Strategy Pattern, Observer Pattern, and Decorator Pattern in Java programs address the concept or method of how existing class objects communicate or behave with each other, and how to manage or organize multiple responsibilities within a user-defined custom class.

Strategy, Observer, Decorator

Strategy Pattern Behavioral/Structural concept in Java.

The Strategy Pattern in Java programs allows Java developers to manually define multiple class algorithms/behaviors and select one of them at runtime.

Example of different Strategy Pattern Behavioral payment methods.

interface PaymentGateway {

void pay();

}

class CreditCardGateway implements PaymentGateway {

@Override

public void pay() {

System.out.println(“Pay with a credit card method”);

}

}

class UpiGateway implements PaymentGateway {

@Override

public void pay() {

System.out.println(“Pay with UPI method”);

}

}

class PaymentMethod {

private PaymentGateway gateway;

public PaymentMethod(PaymentGateway gateway) {

this.gateway = gateway;

}

public void makePaymentMethod() {

gateway.pay();

}

public void setGateway(PaymentGateway gateway) {

this.gateway = gateway;

}

}

public class Main {

public static void main(String[] args) {

// Here we make a payment using Credit Card

PaymentMethod paymentmethod =

new PaymentMethod(new CreditCardGateway());

paymentmethod.makePaymentMethod();

// Here we change the gateway to UPI

paymentmethod.setGateway(new UpiGateway());

paymentmethod.makePaymentMethod();

}

}

its output.

Pay with a credit card method

Pay with UPI method

Here’s the Strategy Pattern Behavioral core idea in this example.

  • Same task → Different algorithm patterns → Program selects at runtime.
  • Real-world examples – Payment methods, sorting algorithms, navigation routes.

Observer Pattern Behavioral/Structural concept in Java.

The Observer pattern in Java programs creates a one-to-many object relationship.

When an object in a user-defined class is modified, all its subscribed class objects automatically become aware of this.

Example of YouTube Subscriber in the Observer Pattern Behavioral/Structural.

import java.util.ArrayList;

import java.util.List;

// Here we create an observer Interface

interface Observer {

void update(String info);

}

// Here we create a class Observer

class Subscriber implements Observer {

private String subscriber_name;

public Subscriber(String subscriber_name) {

this.subscriber_name = subscriber_name;

}

@Override

public void update(String info) {

System.out.println(subscriber_name + ” video updates -: ” + info);

}

}

// here we create a channel Subject

class YouTubeChannel {

private List<Observer> subscribers = new ArrayList<>();

public void subscribe(Observer observer) {

subscribers.add(observer);

}

public void uploadVideo(String video) {

System.out.println(“New channel video uploaded -: ” + video);

for (Observer observer : subscribers) {

observer.update(video);

}

}

}

// here we create a Main Class

public class Main {

public static void main(String[] args) {

YouTubeChannel channel = new YouTubeChannel();

// here we create a youtube channel Subscribe users list

channel.subscribe(new Subscriber(“Bhavishi”));

channel.subscribe(new Subscriber(“Siddhi”));

channel.subscribe(new Subscriber(“Harry”));

// Here we upload a new channel video

channel.uploadVideo(“Strategy, Observer, Decorator tutorial in java”);

}

}

its output.

New channel video uploaded -: Strategy, Observer, Decorator tutorial in java

Bhavishi video updates -: Strategy, Observer, Decorator tutorial in java

Siddhi video updates -: Strategy, Observer, Decorator tutorial in java

Harry video updates -: Strategy, Observer, Decorator tutorial in java

Here’s the Observer Pattern Behavioral main idea in this example.

  • When a class object changes → it notifies multiple class object elements dependent on it simultaneously.
  • Real-world examples → It can be used for notifications like YouTube subscription detail information, live stock-price update alerts, event listener concept, etc.

Decorator Pattern Behavioral/Structural concept in Java.

The Decorator Pattern in Java allows developers to dynamically add new class behaviors/responsibilities to an existing class object without modifying its parent class.

Example of IndianThaliFood Decorator Pattern Behavioral.

// Here we create an IndianThaliFood Interface

interface IndianThaliFood {

String getDescription();

double getCost();

}

// Here we define a basic IndianThaliFood item

class IndianThali implements IndianThaliFood {

@Override

public String getDescription() {

return “Traditional IndianThaliFood”;

}

@Override

public double getCost() {

return 899;

}

}

// Here we create a Decorator method

class RayataDecorator implements IndianThaliFood {

private IndianThaliFood indianthalifood;

public RayataDecorator(IndianThaliFood indianthalifood) {

this.indianthalifood = indianthalifood;

}

@Override

public String getDescription() {

return indianthalifood.getDescription() + ” + Curd Rayata”;

}

@Override

public double getCost() {

return indianthalifood.getCost() + 100;

}

}

// Here we create a main Class

public class Main {

public static void main(String[] args) {

// Here we create a Traditional Indian ThaliFood

IndianThaliFood indianthalifood = new IndianThali();

// Here we create a curd rayata add item detail

indianthalifood = new RayataDecorator(indianthalifood);

//Here we display indian thali details

System.out.println(“Indian Thali Food -: ” + indianthalifood.getDescription());

System.out.println(“Total Cost of Thali In Rs -: ” + indianthalifood.getCost());

}

}

its output.

Indian Thali Food -: Traditional Indian Thali Food + Curd Rayata

Total Cost of Thali In Rs -: 999.0

Java developers can add decorators to their programs like this.

Indian Thali

         ↓

+ Curd Rayata

         ↓

+ Desi Butter Milk

         ↓

+ Papad

         ↓

+Salad

Here’s the Decorator Pattern Behavioral main idea in this example.

In this example, you can add multiple new class features and functionality to a Class object as needed without modifying the original class.

Main Difference Among Strategy, Observer, Decorator Method in Java

#Pattern BehaviourPurpose of Pattern BehaviourApply Method
1.Strategy patternStrategy pattern used to change an algorithm/behavior of object of class with single choiceSelect choose only 1 behavior
2.Observer patternObserver pattern informs or notifies all dependent objects in single or group classAction one → many class object
3.Decorator patternDecorator pattern used to add one or more multiple class functionality dynamically in existing group elementHere it wraps a class object

Conclusion of Strategy, Observer, and Decorator in Java.

  • Strategy Pattern → Selects a single method to perform a task in a Java program.
  • Observer Pattern → Provides simultaneous notifications when an action or event is triggered in a Java program.
  • Decorator Pattern → Adds new features to an existing Group object in a Java program by wrapping the Class object as desired.

Leave a Reply