0% found this document useful (0 votes)
11 views26 pages

Java Design Patterns: Strategy & Command

The document contains multiple Java programs demonstrating various design patterns including Strategy, Observer, Command, Iterator, Adapter, Decorator, and Factory Method. Each section provides a code implementation for a specific pattern, explaining how to create flexible and reusable code structures for different scenarios like sorting algorithms, weather monitoring, remote control systems, and vehicle creation. The examples illustrate the principles of object-oriented design and how to apply design patterns effectively.

Uploaded by

kambalesky4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views26 pages

Java Design Patterns: Strategy & Command

The document contains multiple Java programs demonstrating various design patterns including Strategy, Observer, Command, Iterator, Adapter, Decorator, and Factory Method. Each section provides a code implementation for a specific pattern, explaining how to create flexible and reusable code structures for different scenarios like sorting algorithms, weather monitoring, remote control systems, and vehicle creation. The examples illustrate the principles of object-oriented design and how to apply design patterns effectively.

Uploaded by

kambalesky4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Q1: Write a program in Java implementing strategy pattern for different

sorting techniques.

// [Link]

class SortingContext {

private SortingStrategy sortingStrategy;

public SortingContext(SortingStrategy sortingStrategy) {

[Link] = sortingStrategy;

public void setSortingStrategy(SortingStrategy sortingStrategy) {

[Link] = sortingStrategy;

public void performSort(int[] array) {

[Link](array);

// [Link]

interface SortingStrategy {

void sort(int[] array);

// [Link]
class BubbleSortStrategy implements SortingStrategy {

@Override

public void sort(int[] array) {

// Implement Bubble Sort algorithm

[Link]("Sorting using Bubble Sort");

// Actual Bubble Sort Logic here

// [Link]

class MergeSortStrategy implements SortingStrategy {

@Override

public void sort(int[] array) {

// Implement Merge Sort algorithm

[Link]("Sorting using Merge Sort");

// Actual Merge Sort Logic here

// [Link]

class QuickSortStrategy implements SortingStrategy {

@Override

public void sort(int[] array) {

// Implement Quick Sort algorithm


[Link]("Sorting using Quick Sort");

// Actual Quick Sort Logic here

// [Link]

public class Client {

public static void main(String[] args) {

// Create SortingContext with BubbleSortStrategy

SortingContext sortingContext = new SortingContext(new


BubbleSortStrategy());

int[] array1 = {5, 2, 9, 1, 5};

[Link](array1); // Output: Sorting using Bubble Sort

// Change strategy to MergeSortStrategy

[Link](new MergeSortStrategy());

int[] array2 = {8, 3, 7, 4, 2};

[Link](array2); // Output: Sorting using Merge Sort

// Change strategy to QuickSortStrategy

[Link](new QuickSortStrategy());

int[] array3 = {6, 1, 3, 9, 5};

[Link](array3); // Output: Sorting using Quick Sort

}
Output
Sorting using Bubble Sort
Sorting using Merge Sort
Sorting using Quick Sort

Q2: Write a code to implement observer design pattern where a weather


station is observed by various smart devices. The weather station maintains
a list of registered devices. Weather Station will update all the devices
whenever there is change in the weather.

import [Link];

import [Link];

// Observer Interface

interface Observer {

void update(String weather);

// Subject Interface

interface Subject {

void addObserver(Observer observer);

void removeObserver(Observer observer);

void notifyObservers();

}
// ConcreteSubject Class

class WeatherStation implements Subject {

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

private String weather;

@Override

public void addObserver(Observer observer) {

[Link](observer);

@Override

public void removeObserver(Observer observer) {

[Link](observer);

@Override

public void notifyObservers() {

for (Observer observer : observers) {

[Link](weather);

public void setWeather(String newWeather) {

[Link] = newWeather;
notifyObservers();

// ConcreteObserver Class

class PhoneDisplay implements Observer {

private String weather;

@Override

public void update(String weather) {

[Link] = weather;

display();

private void display() {

[Link]("Phone Display: Weather updated - " + weather);

// ConcreteObserver Class

class TVDisplay implements Observer {

private String weather;

@Override
public void update(String weather) {

[Link] = weather;

display();

private void display() {

[Link]("TV Display: Weather updated - " + weather);

// Usage Class

public class WeatherApp {

public static void main(String[] args) {

WeatherStation weatherStation = new WeatherStation();

Observer phoneDisplay = new PhoneDisplay();

Observer tvDisplay = new TVDisplay();

[Link](phoneDisplay);

[Link](tvDisplay);

// Simulating weather change

[Link]("Sunny");
// Output:

// Phone Display: Weather updated - Sunny

// TV Display: Weather updated - Sunny

Output:
Phone Display: Weather updated - Sunny
TV Display: Weather updated – Sunny

Q3: Write a java program to implement strategy patern for sorting


algorithms
// [Link]
class SortingContext {
private SortingStrategy sortingStrategy;

public SortingContext(SortingStrategy sortingStrategy) {


[Link] = sortingStrategy;
}

public void setSortingStrategy(SortingStrategy sortingStrategy) {


[Link] = sortingStrategy;
}

public void performSort(int[] array) {


[Link](array);
}
}

// [Link]
interface SortingStrategy {
void sort(int[] array);
}

// [Link]
class BubbleSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
// Implement Bubble Sort algorithm
[Link]("Sorting using Bubble Sort");
// Actual Bubble Sort Logic here
}
}

// [Link]
class MergeSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
// Implement Merge Sort algorithm
[Link]("Sorting using Merge Sort");
// Actual Merge Sort Logic here
}
}

// [Link]
class QuickSortStrategy implements SortingStrategy {
@Override
public void sort(int[] array) {
// Implement Quick Sort algorithm
[Link]("Sorting using Quick Sort");
// Actual Quick Sort Logic here
}
}

// [Link]
public class Client {
public static void main(String[] args) {
// Create SortingContext with BubbleSortStrategy
SortingContext sortingContext = new SortingContext(new
BubbleSortStrategy());
int[] array1 = {5, 2, 9, 1, 5};
[Link](array1); // Output: Sorting using Bubble Sort

// Change strategy to MergeSortStrategy


[Link](new MergeSortStrategy());
int[] array2 = {8, 3, 7, 4, 2};
[Link](array2); // Output: Sorting using Merge Sort

// Change strategy to QuickSortStrategy


[Link](new QuickSortStrategy());
int[] array3 = {6, 1, 3, 9, 5};
[Link](array3); // Output: Sorting using Quick Sort
}
}
Output
Sorting using Bubble Sort
Sorting using Merge Sort
Sorting using Quick Sort

Q4: Write a java program to implement command designing a remote


control system for various electronic devices in a smart home. The devices
include a TV, a stereo, and potentially other appliances. The goal is to
create a flexible remote control that can handle different types of
commands for each device, such as turning devices on/off, adjusting
settings, or changing channels.
import [Link];

// Command interface
interface Command {
void execute();
}

// Concrete command for turning a device on


class TurnOnCommand implements Command {
private Consumer<Void> deviceAction;

public TurnOnCommand(Consumer<Void> deviceAction) {


[Link] = deviceAction;
}

@Override
public void execute() {
[Link](null);
}
}

// Concrete command for turning a device off


class TurnOffCommand implements Command {
private Consumer<Void> deviceAction;

public TurnOffCommand(Consumer<Void> deviceAction) {


[Link] = deviceAction;
}

@Override
public void execute() {
[Link](null);
}
}

// Concrete command for adjusting the volume of a stereo


class AdjustVolumeCommand implements Command {
private Runnable stereoAction;

public AdjustVolumeCommand(Runnable stereoAction) {


[Link] = stereoAction;
}

@Override
public void execute() {
[Link]();
}
}

// Concrete command for changing the channel of a TV


class ChangeChannelCommand implements Command {
private Runnable tvAction;

public ChangeChannelCommand(Runnable tvAction) {


[Link] = tvAction;
}

@Override
public void execute() {
[Link]();
}
}

// Receiver interface
interface Device {
void turnOn();
void turnOff();
}

// Concrete receiver for a TV


class TV implements Device {
@Override
public void turnOn() {
[Link]("TV is now on");
}

@Override
public void turnOff() {
[Link]("TV is now off");
}

public void changeChannel() {


[Link]("Channel changed");
}
}

// Concrete receiver for a stereo


class Stereo implements Device {
@Override
public void turnOn() {
[Link]("Stereo is now on");
}

@Override
public void turnOff() {
[Link]("Stereo is now off");
}

public void adjustVolume() {


[Link]("Volume adjusted");
}
}

// Invoker
class RemoteControl {
private Command command;

public void setCommand(Command command) {


[Link] = command;
}

public void pressButton() {


if (command != null) {
[Link]();
}
}
}

// Example usage
public class Main {
public static void main(String[] args) {
// Create devices
TV tv = new TV();
Stereo stereo = new Stereo();

// Create command objects


Command turnOnTvCommand = new TurnOnCommand(tv::turnOn);
Command turnOffTvCommand = new TurnOffCommand(tv::turnOff);
Command adjustVolumeStereoCommand = new
AdjustVolumeCommand(stereo::adjustVolume);
Command changeChannelTvCommand = new
ChangeChannelCommand(tv::changeChannel);

// Create remote control


RemoteControl remote = new RemoteControl();

// Set and execute commands


[Link](turnOnTvCommand);
[Link](); // Outputs: TV is now on

[Link](adjustVolumeStereoCommand);
[Link](); // Outputs: Volume adjusted

[Link](changeChannelTvCommand);
[Link](); // Outputs: Channel changed

[Link](turnOffTvCommand);
[Link](); // Outputs: TV is now off
}
}
Output
TV is now on
Volume adjusted
Channel changed
TV is now off
Q5: Write a java program to implement iterator pattern for generating
salary employee:
import [Link].*;

// Employee class
class Employee {
private String name;
private double salary;

public Employee(String name, double salary) {


[Link] = name;
[Link] = salary;
}

public double getSalary() {


return salary;
}
}

// Iterator interface
interface Iterator<T> {
boolean hasNext();
T next();
}

// Aggregate interface
interface Aggregate<T> {
Iterator<T> createIterator();
}

// Concrete Iterator
class EmployeeIterator implements Iterator<Employee> {
private int currentIndex = 0;
private List<Employee> employees;

public EmployeeIterator(List<Employee> employees) {


[Link] = employees;
}

@Override
public boolean hasNext() {
return currentIndex < [Link]();
}

@Override
public Employee next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return [Link](currentIndex++);
}
}

// Concrete Aggregate
class Company implements Aggregate<Employee> {
private List<Employee> employees;

public Company(List<Employee> employees) {


[Link] = employees;
}

@Override
public Iterator<Employee> createIterator() {
return new EmployeeIterator(employees);
}
}

// Main class
public class Main {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
[Link](new Employee("Alice", 50000));
[Link](new Employee("Bob", 60000));
[Link](new Employee("Charlie", 70000));

Company company = new Company(employees);


Iterator<Employee> iterator = [Link]();

double totalSalary = 0;
while ([Link]()) {
totalSalary += [Link]().getSalary();
}

[Link]("Total salary: " + totalSalary);


}
}
Output:
Total salary: 180000.0

Q 6: Write a java program to implement adapter design pattern existing


system that uses a LegacyPrinter class with a method named
printDocument() which we want to adapt into a new system that expects a
Printer interface with a method named print(). We'll use the Adapter
design pattern to make these two interfaces compatible.

/* Adapter Design Pattern Example Code */

// Target Interface
interface Printer {
void print();
}

// Adaptee
class LegacyPrinter {
public void printDocument() {
[Link]("Legacy Printer is printing a document.");
}
}

// Adapter
class PrinterAdapter implements Printer {
private LegacyPrinter legacyPrinter = new LegacyPrinter();

@Override
public void print() {
[Link]();
}
}

// Client Code
public class Client {
public static void clientCode(Printer printer) {
[Link]();
}

public static void main(String[] args) {


// Using the Adapter
PrinterAdapter adapter = new PrinterAdapter();
clientCode(adapter);
}
}

Output
Legacy Printer is printing a document.

Q 7: Write a java program to implement decorator pattern coffee shop


application where customers can order different types of coffee. Each
coffee can have various optional add-ons such as milk, sugar, whipped
cream, etc. We want to implement a system where we can dynamically
add these add-ons to a coffee order without modifying the coffee classes
themselves.

// [Link]

public interface Coffee {

String getDescription();

double getCost();

// [Link]

public class PlainCoffee implements Coffee {

@Override

public String getDescription() {

return "Plain Coffee";

@Override

public double getCost() {


return 2.0;

// [Link]

public abstract class CoffeeDecorator implements Coffee {

protected Coffee decoratedCoffee;

public CoffeeDecorator(Coffee decoratedCoffee) {

[Link] = decoratedCoffee;

@Override

public String getDescription() {

return [Link]();

@Override

public double getCost() {

return [Link]();

// [Link]
public class MilkDecorator extends CoffeeDecorator {

public MilkDecorator(Coffee decoratedCoffee) {

super(decoratedCoffee);

@Override

public String getDescription() {

return [Link]() + ", Milk";

@Override

public double getCost() {

return [Link]() + 0.5;

// [Link]

public class SugarDecorator extends CoffeeDecorator {

public SugarDecorator(Coffee decoratedCoffee) {

super(decoratedCoffee);

@Override

public String getDescription() {


return [Link]() + ", Sugar";

@Override

public double getCost() {

return [Link]() + 0.2;

// [Link]

public class Main {

public static void main(String[] args) {

// Plain Coffee

Coffee coffee = new PlainCoffee();

[Link]("Description: " + [Link]());

[Link]("Cost: $" + [Link]());

// Coffee with Milk

Coffee milkCoffee = new MilkDecorator(new PlainCoffee());

[Link]("\nDescription: " + [Link]());

[Link]("Cost: $" + [Link]());

// Coffee with Sugar and Milk

Coffee sugarMilkCoffee = new SugarDecorator(new MilkDecorator(new


PlainCoffee()));
[Link]("\nDescription: " + [Link]());

[Link]("Cost: $" + [Link]());

Output:

Description: Plain Coffee

Cost: $2.0

Description: Plain Coffee, Milk

Cost: $2.5

Description: Plain Coffee, Milk, Sugar

Cost: $2.7

Q:8 Write a java program to implement using factory method the


creation of various types of vehicles, such as Two Wheelers, Three
Wheelers, and Four Wheelers. Each type of vehicle has its own specific
properties and behaviors.

/ Library classes

abstract class Vehicle {

public abstract void printVehicle();

class TwoWheeler extends Vehicle {

public void printVehicle() {


[Link]("I am two wheeler");

class FourWheeler extends Vehicle {

public void printVehicle() {

[Link]("I am four wheeler");

// Factory Interface

interface VehicleFactory {

Vehicle createVehicle();

// Concrete Factory for TwoWheeler

class TwoWheelerFactory implements VehicleFactory {

public Vehicle createVehicle() {

return new TwoWheeler();

// Concrete Factory for FourWheeler

class FourWheelerFactory implements VehicleFactory {


public Vehicle createVehicle() {

return new FourWheeler();

// Client class

class Client {

private Vehicle pVehicle;

public Client(VehicleFactory factory) {

pVehicle = [Link]();

public Vehicle getVehicle() {

return pVehicle;

// Driver program

public class GFG {

public static void main(String[] args) {

VehicleFactory twoWheelerFactory = new TwoWheelerFactory();

Client twoWheelerClient = new Client(twoWheelerFactory);

Vehicle twoWheeler = [Link]();


[Link]();

VehicleFactory fourWheelerFactory = new FourWheelerFactory();

Client fourWheelerClient = new Client(fourWheelerFactory);

Vehicle fourWheeler = [Link]();

[Link]();

Output
I am two wheeler
I am four wheeler

Q: 9 write a java program to implement singleton pattern for


multithreading

public class ThreadSafeSingleton {

// volatile keyword ensures that multiple threads correctly handle the instance
variable

private static volatile ThreadSafeSingleton instance;

// Private constructor to prevent direct instantiation from outside the class

private ThreadSafeSingleton() {

// Optional: Add a check here to prevent reflection-based instantiation

if (instance != null) {
throw new RuntimeException("Use getInstance() to get the single
instance of this class.");

// Public static method to provide the global access point for the single
instance

public static ThreadSafeSingleton getInstance() {

// First check: Reduces synchronization overhead if instance is already


created

if (instance == null) {

// Synchronized block to ensure only one thread initializes the instance

synchronized ([Link]) {

// Second check: Essential to prevent multiple instances in a multi-


threaded environment

if (instance == null) {

instance = new ThreadSafeSingleton();

return instance;

// Example method to demonstrate functionality

public void showMessage() {

[Link]("Hello from the Singleton instance!");


}

public static void main(String[] args) {

// Simulate multiple threads trying to get the Singleton instance

Thread t1 = new Thread(() -> {

ThreadSafeSingleton s1 = [Link]();

[Link]("Thread 1: " + [Link]());

[Link]();

});

Thread t2 = new Thread(() -> {

ThreadSafeSingleton s2 = [Link]();

[Link]("Thread 2: " + [Link]());

[Link]();

});

[Link]();

[Link]();

You might also like