0% found this document useful (0 votes)
996 views58 pages

Java Weather Station Implementation

The document describes a Java program that implements the observer design pattern to model a weather station. It includes classes like WeatherData, CurrentConditionsDisplay, StatisticsDisplay, and ForecastDisplay. WeatherData is the subject that stores temperature, humidity, and pressure measurements. The display classes like CurrentConditionsDisplay are observers that register with WeatherData and are notified of measurement changes to update their displays. The program is run with some sample measurement data to demonstrate the observer pattern implementation.

Uploaded by

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

Java Weather Station Implementation

The document describes a Java program that implements the observer design pattern to model a weather station. It includes classes like WeatherData, CurrentConditionsDisplay, StatisticsDisplay, and ForecastDisplay. WeatherData is the subject that stores temperature, humidity, and pressure measurements. The display classes like CurrentConditionsDisplay are observers that register with WeatherData and are notified of measurement changes to update their displays. The program is run with some sample measurement data to demonstrate the observer pattern implementation.

Uploaded by

Jidnesh Ghorpade
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Practical 1: Weather Station
  • Practical 2: IO Decorator
  • Practical 3: Pizza Factory
  • Practical 4: Chocolate Boiler
  • Practical 5: Remote Control
  • Practical 6: Ceiling Fan with Undo
  • Practical 7: Adapter Pattern
  • Practical 8: Iterator Pattern for Menu
  • Practical 10: Heart Model MVC
  • Practical 9: Gumball Machine State

Name: Tanmay Kolekar

Subject: SADP Practical Sol​n​.


Roll No.: 421

Practical 1:
Write a JAVA Program to implement built-in support ([Link]) Weather station with
members temperature, humidity, pressure and methods mesurmentsChanged(),
setMesurment(), getTemperature(), getHumidity(),getPressure()

[Link]:

public interface DisplayElement


{
public void display();
}

[Link]:

public interface Observer


{
public void update(float temp, float humidity, float pressure);
}

[Link]:

public interface Subject


{
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}

[Link]:

import [Link].*;
public class WeatherData implements Subject
{
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData()
{
observers = new ArrayList<>();
}
public void registerObserver(Observer o)
{
[Link](o);
}
public void removeObserver(Observer o)
{
int i = [Link](o);
if (i >= 0)
{
[Link](i);
}
}
public void notifyObservers()
{
for (int i = 0; i < [Link](); i++)
{
Observer observer = (Observer)[Link](i);
[Link](temperature, humidity, pressure);
}
}
public void measurementsChanged()
{
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure)
{
[Link] = temperature;
[Link] = humidity;
[Link] = pressure;
measurementsChanged();
}
public float getTemperature()
{
return temperature;
}
public float getHumidity()
{
return humidity;
}
public float getPressure()
{
return pressure;
}
}

[Link]:

class ForecastDisplay implements Observer, DisplayElement


{
private float currentPressure = 29.92f;
private float lastPressure;
private WeatherData weatherData;

public ForecastDisplay(WeatherData weatherData)


{
[Link] = weatherData;
[Link](this);
}
public void update(float temp, float humidity, float pressure)
{
lastPressure = currentPressure;
currentPressure = pressure;
display();
}
public void display()
{
[Link]("Forecast: ");
if (currentPressure > lastPressure)
{
[Link]("Improving weather on the way!");
}
else if (currentPressure == lastPressure)
{
[Link]("More of the same");
}
else if (currentPressure < lastPressure)
{
[Link]("Watch out for cooler, rainy weather");
}
}
}

[Link]
class StatisticsDisplay implements Observer, DisplayElement
{
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum= 0.0f;
private int numReadings;
private WeatherData weatherData;
public StatisticsDisplay(WeatherData weatherData)
{
[Link] = weatherData;
[Link](this);
}
public void update(float temp, float humidity, float pressure)
{
tempSum += temp;
numReadings++;
if (temp > maxTemp)
{
maxTemp = temp;
}
if (temp < minTemp)
{
minTemp = temp;
}
display();
}
public void display()
{
[Link]("Avg/Max/Min temperature = " + (tempSum / numReadings)+
"/" + maxTemp + "/" + minTemp);
}
}

[Link]:

class CurrentConditionsDisplay implements Observer, DisplayElement


{
private float temperature;
private float humidity;
private Subject weatherData;

public CurrentConditionsDisplay(Subject weatherData)


{
[Link] = weatherData;
[Link](this);
}

public void update(float temperature, float humidity, float pressure)


{
[Link] = temperature;
[Link] = humidity;
display();
}

public void display()


{
[Link]("Current conditions: " + temperature+ "F degrees and " +
humidity + "% humidity");
}
}

[Link]:

class WeatherStation
{
public static void main(String[] args)
{
WeatherData weatherData = new WeatherData();

CurrentConditionsDisplay currentDisplay=new
CurrentConditionsDisplay(weatherData);
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);

[Link](80, 65, 30.4f);


[Link](82, 70, 29.2f);
[Link](78, 90, 29.2f);
}
}

/*
Output:
D:\MScSem3Practicals\SADP Pract Assignment\Pract1>javac [Link]

D:\MScSem3Practicals\SADP Pract Assignment\Pract1>java WeatherStation


Current conditions: 80.0F degrees and 65.0% humidity
Avg/Max/Min temperature = 80.0/80.0/80.0
Forecast: Improving weather on the way!
Current conditions: 82.0F degrees and 70.0% humidity
Avg/Max/Min temperature = 81.0/82.0/80.0
Forecast: Watch out for cooler, rainy weather
Current conditions: 78.0F degrees and 90.0% humidity
Avg/Max/Min temperature = 80.0/82.0/78.0
Forecast: More of the same

*/
Practical 2:
Write a Java Program to implement I/O Decorator for converting uppercase letters to lower case
letters.

[Link]

import [Link].*;
public class LowerCaseInputStream extends FilterInputStream
{
public LowerCaseInputStream(InputStream in)
{
super(in);
}
public int read() throws IOException
{
int c = [Link]();
return (c == -1 ? c : [Link]((char)c));
}
public int read(byte[] b, int offset, int len) throws IOException
{
int result = [Link](b, offset, len);
for (int i = offset; i < offset+result; i++)
{
b[i] = (byte)[Link]((char)b[i]);
}
return result;
}
}

[Link]:

import [Link].*;
public class InputTest
{
public static void main(String[] args) throws IOException
{
int c;
try
{
InputStream in = new LowerCaseInputStream(new BufferedInputStream(new
FileInputStream("[Link]")));
while((c = [Link]()) >= 0)
{
[Link]((char)c);
}
[Link]();
}
catch (IOException e)
{
[Link]();
}
}
}

/*
Input: [Link]:
Hello
How are YOU!!?

Output:
D:\MScSem3Practicals\SADP Pract Assignment\Pract2>java InputTest
hello
how are you!!?
D:\MScSem3Practicals\SADP Pract Assignment\Pract2>
*/
Practical 3:
Write a Java Program to implement Factory method for Pizza Store with createPizza(),
orederPizza(), prepare(), Bake(), cut(), box(). Use this to create variety of pizza’s like
NyStyleCheesePizza, ChicagoStyleCheesePizza etc.

[Link]:

import [Link];
abstract class Pizza
{
String name;
String dough;
String sauce;
ArrayList toppings = new ArrayList();
void prepare()
{
[Link]("Preparing " + name);
[Link]("Tossing dough...");
[Link]("Adding sauce...");
[Link]("Adding toppings: ");
for (int i = 0; i < [Link](); i++)
{
[Link](" " + [Link](i));
}
}
void bake()
{
[Link]("Bake for 25 minutes at 350");
}
void cut()
{
[Link]("Cutting the pizza into diagonal slices");
}
void box()
{
[Link]("Place pizza in official PizzaStore box");
}
public String getName()
{
return name;
}
public String toString()
{
StringBuffer display = new StringBuffer();
[Link]("---- " + name + " ----\n");
[Link](dough + "\n");
[Link](sauce + "\n");
for (int i = 0; i < [Link](); i++)
{
[Link]((String )[Link](i) + "\n");
}
return [Link]();
}
}

class ChicagoStyleCheesePizza extends Pizza


{
public ChicagoStyleCheesePizza()
{
name = "Chicago Style Deep Dish Cheese Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
[Link]("Shredded Mozzarella Cheese");
}
void cut()
{
[Link]("Cutting the pizza into square slices");
}
}

class ChicagoStyleClamPizza extends Pizza


{
public ChicagoStyleClamPizza()
{
name = "Chicago Style Clam Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
[Link]("Shredded Mozzarella Cheese");
[Link]("Frozen Clams from Chesapeake Bay");
}
void cut()
{
[Link]("Cutting the pizza into square slices");
}
}

class ChicagoStylePepperoniPizza extends Pizza


{
public ChicagoStylePepperoniPizza()
{
name = "Chicago Style Pepperoni Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
[Link]("Shredded Mozzarella Cheese");
[Link]("Black Olives");
[Link]("Spinach");
[Link]("Eggplant");
[Link]("Sliced Pepperoni");
}
void cut()
{
[Link]("Cutting the pizza into square slices");
}
}

class ChicagoStyleVeggiePizza extends Pizza


{
public ChicagoStyleVeggiePizza()
{
name = "Chicago Deep Dish Veggie Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
[Link]("Shredded Mozzarella Cheese");
[Link]("Black Olives");
[Link]("Spinach");
[Link]("Eggplant");
}
void cut()
{
[Link]("Cutting the pizza into square slices");
}
}

class NYStyleCheesePizza extends Pizza


{
public NYStyleCheesePizza()
{
name = "NY Style Sauce and Cheese Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
[Link]("Grated Reggiano Cheese");
}
}

class NYStyleClamPizza extends Pizza


{
public NYStyleClamPizza()
{
name = "NY Style Clam Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
[Link]("Grated Reggiano Cheese");
[Link]("Fresh Clams from Long Island Sound");
}
}

class NYStylePepperoniPizza extends Pizza


{
public NYStylePepperoniPizza()
{
name = "NY Style Pepperoni Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
[Link]("Grated Reggiano Cheese");
[Link]("Sliced Pepperoni");
[Link]("Garlic");
[Link]("Onion");
[Link]("Mushrooms");
[Link]("Red Pepper");
}
}

class NYStyleVeggiePizza extends Pizza


{
public NYStyleVeggiePizza()
{
name = "NY Style Veggie Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
[Link]("Grated Reggiano Cheese");
[Link]("Garlic");
[Link]("Onion");
[Link]("Mushrooms");
[Link]("Red Pepper");
}
}

abstract class PizzaStore


{
abstract Pizza createPizza(String item);
public Pizza orderPizza(String type)
{
Pizza pizza = createPizza(type);
[Link]("--- Making a " + [Link]() + "---"); [Link]();
[Link]();
[Link]();
[Link]();
return pizza;
}
}

class ChicagoPizzaStore extends PizzaStore


{
Pizza createPizza(String item)
{
if ([Link]("cheese"))
{
return new ChicagoStyleCheesePizza();
}
else if ([Link]("veggie"))
{
return new ChicagoStyleVeggiePizza();
}
else if ([Link]("clam"))
{
return new ChicagoStyleClamPizza();
}
else if ([Link]("pepperoni"))
{
return new ChicagoStylePepperoniPizza();
}
else
return null;
}
}

class NYPizzaStore extends PizzaStore


{
Pizza createPizza(String item)
{
if ([Link]("cheese"))
{
return new NYStyleCheesePizza();
}
else if ([Link]("veggie"))
{
return new NYStyleVeggiePizza();
}
else if ([Link]("clam"))
{
return new NYStyleClamPizza();
}
else if ([Link]("pepperoni"))
{
return new NYStylePepperoniPizza();
}
else
return null;
}
}

public class PizzaFactoryDemo


{
public static void main(String[] args)
{
PizzaStore nyStore = new NYPizzaStore();
PizzaStore chicagoStore = new ChicagoPizzaStore();
Pizza pizza = [Link]("cheese");
[Link]("Customer1 ordered a " + [Link]() +"\n");
pizza = [Link]("cheese");
[Link]("Customer2 ordered a " + [Link]() +"\n");
pizza = [Link]("clam");
[Link]("Customer1 ordered a " + [Link]() +"\n");
pizza = [Link]("clam");
[Link]("Customer2 ordered a " + [Link]() +"\n");
pizza = [Link]("pepperoni");
[Link]("Customer1 ordered a " + [Link]() +"\n");
pizza = [Link]("pepperoni");
[Link]("Customer2 ordered a " + [Link]() +"\n");
pizza = [Link]("veggie");
[Link]("Customer1 ordered a " + [Link]() +"\n");
pizza = [Link]("veggie");
[Link]("Customer2 ordered a " + [Link]() +"\n");
}
}

/*
Output:

Microsoft Windows [Version 10.0.19041.685]


(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract3>java PizzaFactoryDemo


--- Making a NY Style Sauce and Cheese Pizza---
Preparing NY Style Sauce and Cheese Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Grated Reggiano Cheese
Bake for 25 minutes at 350
Cutting the pizza into diagonal slices
Place pizza in official PizzaStore box
Customer1 ordered a NY Style Sauce and Cheese Pizza

--- Making a Chicago Style Deep Dish Cheese Pizza---


Preparing Chicago Style Deep Dish Cheese Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Shredded Mozzarella Cheese
Bake for 25 minutes at 350
Cutting the pizza into square slices
Place pizza in official PizzaStore box
Customer2 ordered a Chicago Style Deep Dish Cheese Pizza

--- Making a NY Style Clam Pizza---


Preparing NY Style Clam Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Grated Reggiano Cheese
Fresh Clams from Long Island Sound
Bake for 25 minutes at 350
Cutting the pizza into diagonal slices
Place pizza in official PizzaStore box
Customer1 ordered a NY Style Clam Pizza
--- Making a Chicago Style Clam Pizza---
Preparing Chicago Style Clam Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Shredded Mozzarella Cheese
Frozen Clams from Chesapeake Bay
Bake for 25 minutes at 350
Cutting the pizza into square slices
Place pizza in official PizzaStore box
Customer2 ordered a Chicago Style Clam Pizza

--- Making a NY Style Pepperoni Pizza---


Preparing NY Style Pepperoni Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Grated Reggiano Cheese
Sliced Pepperoni
Garlic
Onion
Mushrooms
Red Pepper
Bake for 25 minutes at 350
Cutting the pizza into diagonal slices
Place pizza in official PizzaStore box
Customer1 ordered a NY Style Pepperoni Pizza

--- Making a Chicago Style Pepperoni Pizza---


Preparing Chicago Style Pepperoni Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Shredded Mozzarella Cheese
Black Olives
Spinach
Eggplant
Sliced Pepperoni
Bake for 25 minutes at 350
Cutting the pizza into square slices
Place pizza in official PizzaStore box
Customer2 ordered a Chicago Style Pepperoni Pizza
--- Making a NY Style Veggie Pizza---
Preparing NY Style Veggie Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Grated Reggiano Cheese
Garlic
Onion
Mushrooms
Red Pepper
Bake for 25 minutes at 350
Cutting the pizza into diagonal slices
Place pizza in official PizzaStore box
Customer1 ordered a NY Style Veggie Pizza

--- Making a Chicago Deep Dish Veggie Pizza---


Preparing Chicago Deep Dish Veggie Pizza
Tossing dough...
Adding sauce...
Adding toppings:
Shredded Mozzarella Cheese
Black Olives
Spinach
Eggplant
Bake for 25 minutes at 350
Cutting the pizza into square slices
Place pizza in official PizzaStore box
Customer2 ordered a Chicago Deep Dish Veggie Pizza

*/
Practical 4:
Write a Java Program to implement Singleton pattern for multithreading.

[Link]:

class ChocolateBoiler
{
private boolean empty;
private boolean boiled;
private static ChocolateBoiler uniqueInstance;

private ChocolateBoiler()
{
empty = true;
boiled = false;
}

public static synchronized ChocolateBoiler getInstance()


{
if (uniqueInstance == null)
{
[Link]("Creating unique instance of Chocolate Boiler");
uniqueInstance = new ChocolateBoiler();
}
[Link]("Returning instance of Chocolate Boiler");
return uniqueInstance;
}

public void fill(String threadName)


{
if (isEmpty())
{
empty = false;
boiled = false;
[Link](threadName+ ": The boiler is filled with a
milk/chocolate mixture");
}
}

public void drain(String threadName)


{
if (!isEmpty() && isBoiled())
{
[Link](threadName +": Drain the boiled milk and chocolate");
empty = true;
}
}

public void boil(String threadName)


{
if (!isEmpty() && !isBoiled())
{
[Link](threadName +": Bring the contents to a boil");
boiled = true;
}
}

public boolean isEmpty()


{
return empty;
}

public boolean isBoiled()


{
return boiled;
}
}

class ChocolateController implements Runnable


{
private Thread t;
private String threadName;
private ChocolateBoiler boiler;

ChocolateController( String name)


{
threadName = name;
[Link]("Creating " + threadName);
boiler = [Link]();
}

public void run()


{
[Link]("Running " + threadName +" with boiler instance "+boiler );
try
{
[Link](threadName);
[Link](threadName);
[Link](threadName);
// Let the thread sleep for a while.
[Link](50);
}
catch (InterruptedException e)
{
[Link]("Thread " + threadName + " interrupted.");
}
[Link]("Thread " + threadName + " exiting.");
}

public void start ()


{
[Link]("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
[Link] ();
}
}
}

[Link]:

public class ChocolateControllerDemo


{
public static void main(String args[])
{
ChocolateController t1 = new ChocolateController( "Thread-1");
[Link]();
ChocolateController t2 = new ChocolateController( "Thread-2");
[Link]();
}
}

/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract4>java ChocolateControllerDemo


Creating Thread-1
Creating unique instance of Chocolate Boiler
Returning instance of Chocolate Boiler
Starting Thread-1
Creating Thread-2
Returning instance of Chocolate Boiler
Running Thread-1 with boiler instance ChocolateBoiler@4c31f4d0
Starting Thread-2
Thread-1: The boiler is filled with a milk/chocolate mixture
Thread-1: Bring the contents to a boil
Thread-1: Drain the boiled milk and chocolate
Running Thread-2 with boiler instance ChocolateBoiler@4c31f4d0
Thread-2: The boiler is filled with a milk/chocolate mixture
Thread-2: Bring the contents to a boil
Thread-2: Drain the boiled milk and chocolate
Thread Thread-2 exiting.
Thread Thread-1 exiting.

*/
Practical 5:
Write a Java Program to implement command pattern to test Remote Control.

[Link]

interface Command
{
public void execute();
}

class Light
{
public void on()
{
[Link]("Light is on");
}
public void off()
{
[Link]("Light is off");
}
}
class LightOnCommand implements Command
{
Light light;

public LightOnCommand(Light light)


{
[Link] = light;
}
public void execute()
{
[Link]();
}
}
class LightOffCommand implements Command
{
Light light;
public LightOffCommand(Light light)
{
[Link] = light;
}
public void execute()
{
[Link]();
}
}

class Stereo
{
public void on()
{
[Link]("Stereo is on");
}
public void off()
{
[Link]("Stereo is off");
}
public void setCD()
{
[Link]("Stereo is set " +"for CD input");
}
public void setDVD()
{
[Link]("Stereo is set"+" for DVD input");
}
public void setRadio()
{
[Link]("Stereo is set" +" for Radio");
}
public void setVolume(int volume)
{
[Link]("Stereo volume set"+ " to " + volume);
}
}

class StereoOffCommand implements Command


{
Stereo stereo;
public StereoOffCommand(Stereo stereo)
{
[Link] = stereo;
}
public void execute()
{
[Link]();
}
}
class StereoOnWithCDCommand implements Command
{
Stereo stereo;
public StereoOnWithCDCommand(Stereo stereo)
{
[Link] = stereo;
}
public void execute()
{
[Link]();
[Link]();
[Link](11);
}
}

class SimpleRemoteControl
{
Command slot;

public SimpleRemoteControl()
{
}

public void setCommand(Command command)


{
slot = command;
}

public void buttonWasPressed()


{
[Link]();
}
}

// Driver class
class RemoteControlTest
{
public static void main(String[] args)
{
SimpleRemoteControl remote =new SimpleRemoteControl();
Light light = new Light();
Stereo stereo = new Stereo();

[Link](new LightOnCommand(light));
[Link]();
[Link](new StereoOnWithCDCommand(stereo));
[Link]();
[Link](new StereoOffCommand(stereo));
[Link]();
}
}

/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract5>java RemoteControlTest


Light is on
Stereo is on
Stereo is set for CD input
Stereo volume set to 11
Stereo is off
*/
Practical 6:
Write a Java Program to implement undo command to test Ceiling fan.

[Link]:

public class RemoteLoader


{
public static void main(String[] args)
{
RemoteControlWithUndo remoteControl = new RemoteControlWithUndo();

CeilingFan ceilingFan = new CeilingFan("Living Room");


CeilingFanMediumCommand ceilingFanMedium=new
CeilingFanMediumCommand(ceilingFan);
CeilingFanHighCommand ceilingFanHigh=new
CeilingFanHighCommand(ceilingFan);
CeilingFanOffCommand ceilingFanOff=new CeilingFanOffCommand(ceilingFan);

[Link](0, ceilingFanMedium, ceilingFanOff);


[Link](1, ceilingFanHigh, ceilingFanOff);

[Link](0);
[Link](0);
[Link](remoteControl);
[Link]();

[Link](1);
[Link](remoteControl);
[Link]();
}
}

/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract6>java RemoteLoader


Living Room ceiling fan is on medium
Living Room ceiling fan is off

------ Remote Control -------


[slot 0] CeilingFanMediumCommand CeilingFanOffCommand
[slot 1] CeilingFanHighCommand CeilingFanOffCommand
[slot 2] NoCommand NoCommand
[slot 3] NoCommand NoCommand
[slot 4] NoCommand NoCommand
[slot 5] NoCommand NoCommand
[slot 6] NoCommand NoCommand
[undo] CeilingFanOffCommand

Living Room ceiling fan is on medium


Living Room ceiling fan is on high

------ Remote Control -------


[slot 0] CeilingFanMediumCommand CeilingFanOffCommand
[slot 1] CeilingFanHighCommand CeilingFanOffCommand
[slot 2] NoCommand NoCommand
[slot 3] NoCommand NoCommand
[slot 4] NoCommand NoCommand
[slot 5] NoCommand NoCommand
[slot 6] NoCommand NoCommand
[undo] CeilingFanHighCommand

Living Room ceiling fan is on medium

*/

[Link]:

import [Link].*;
public class RemoteControlWithUndo {
Command[] onCommands;
Command[] offCommands;
Command undoCommand;

public RemoteControlWithUndo() {
onCommands = new Command[7];
offCommands = new Command[7];

Command noCommand = new NoCommand();


for(int i=0;i<7;i++) {
onCommands[i] = noCommand;
offCommands[i] = noCommand;
}
undoCommand = noCommand;
}

public void setCommand(int slot, Command onCommand, Command offCommand) {


onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}

public void onButtonWasPushed(int slot) {


onCommands[slot].execute();
undoCommand = onCommands[slot];
}

public void offButtonWasPushed(int slot) {


offCommands[slot].execute();
undoCommand = offCommands[slot];
}

public void undoButtonWasPushed() {


[Link]();
}

public String toString() {


StringBuffer stringBuff = new StringBuffer();
[Link]("\n------ Remote Control -------\n");
for (int i = 0; i < [Link]; i++) {
[Link]("[slot " + i + "] " +
onCommands[i].getClass().getName()+ " " + offCommands[i].getClass().getName() + "\n");
}
[Link]("[undo] " + [Link]().getName() + "\n");
return [Link]();
}
}

[Link]:

public class CeilingFanOffCommand implements Command {


CeilingFan ceilingFan;
int prevSpeed;

public CeilingFanOffCommand(CeilingFan ceilingFan) {


[Link] = ceilingFan;
}
public void execute() {
prevSpeed = [Link]();
[Link]();
}

public void undo() {


if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
}
}
}

[Link]:

public class CeilingFanMediumCommand implements Command {


CeilingFan ceilingFan;
int prevSpeed;

public CeilingFanMediumCommand(CeilingFan ceilingFan) {


[Link] = ceilingFan;
}

public void execute() {


prevSpeed = [Link]();
[Link]();
}

public void undo() {


if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
}
}
}

[Link]:

public class CeilingFanLowCommand implements Command {


CeilingFan ceilingFan;
int prevSpeed;

public CeilingFanLowCommand(CeilingFan ceilingFan) {


[Link] = ceilingFan;
}

public void execute() {


prevSpeed = [Link]();
[Link]();
}

public void undo() {


if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
}
}
}

[Link]:

public class CeilingFanHighCommand implements Command {


CeilingFan ceilingFan;
int prevSpeed;

public CeilingFanHighCommand(CeilingFan ceilingFan) {


[Link] = ceilingFan;
}

public void execute() {


prevSpeed = [Link]();
[Link]();
}

public void undo() {


if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
} else if (prevSpeed == [Link]) {
[Link]();
}
}
}

[Link]

public class CeilingFan {


public static final int HIGH = 3;
public static final int MEDIUM = 2;
public static final int LOW = 1;
public static final int OFF = 0;
String location;
int speed;

public CeilingFan(String location) {


[Link] = location;
speed = OFF;
}

public void high() {


speed = HIGH;
[Link](location + " ceiling fan is on high");
}

public void medium() {


speed = MEDIUM;
[Link](location + " ceiling fan is on medium");
}

public void low()


{
speed = LOW;
[Link](location + " ceiling fan is on low");
}

public void off() {


speed = OFF;
[Link](location + " ceiling fan is off");
}

public int getSpeed() {


return speed;
}
}

[Link]:

public interface Command


{
public void execute();
public void undo();
}

[Link]:

public class NoCommand implements Command {


public void execute() { }
public void undo() { }
}
Practical 7:
Write a Java Program to implement Adapter pattern for Enumeration iterator.

[Link]

import [Link].*;
public class EnumerationIterator implements Iterator {
Enumeration enumeration;

public EnumerationIterator(Enumeration enumeration) {


[Link] = enumeration;
}

public boolean hasNext() {


return [Link]();
}

public Object next() {


return [Link]();
}

public void remove() {


throw new UnsupportedOperationException();
}
}

[Link]:

import [Link].*;
public class EnumerationIteratorTestDrive
{
public static void main (String args[])
{
Vector v = new Vector([Link](args));
Iterator iterator = new EnumerationIterator([Link]());
while ([Link]())
{
[Link]([Link]());
}
}
}
/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract7>java EnumerationIteratorTestDrive hi


hello how are you ?
hi
hello
how
are
you
?
*/
Practical 8:
Write a Java Program to implement Iterator Pattern for Designing Menu like
Breakfast, Lunch or Dinner Menu. Book 6 (page no 326)

[Link]:

import [Link].*;
public class MenuTestDrive
{
public static void main(String args[])
{
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu();
Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
[Link]();
[Link]();

[Link]("\nCustomer asks, is the Hotdog vegetarian?");


[Link]("Waitress says: ");
if ([Link]("Hotdog"))
{
[Link]("Yes");
}
else
{
[Link]("No");
}
[Link]("\nCustomer asks, are the Waffles vegetarian?");
[Link]("Waitress says: ");
if ([Link]("Waffles"))
{
[Link]("Yes");
}
else
{
[Link]("No");
}

}
}

/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract8\>java MenuTestDrive


MENU
----
BREAKFAST
K&B's Pancake Breakfast, 2.99 -- Pancakes with scrambled eggs, and toast
Regular Pancake Breakfast, 2.99 -- Pancakes with fried eggs, sausage
Blueberry Pancakes, 3.49 -- Pancakes made with fresh blueberries, and blueberry syrup
Waffles, 3.59 -- Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT, 2.99 -- (Fakin') Bacon with lettuce & tomato on whole wheat
BLT, 2.99 -- Bacon with lettuce & tomato on whole wheat
Soup of the day, 3.29 -- Soup of the day, with a side of potato salad
Hotdog, 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese
Steamed Veggies and Brown Rice, 3.99 -- Steamed vegetables over brown rice
Pasta, 3.89 -- Spaghetti with Marinara Sauce, and a slice of sourdough bread

VEGETARIAN MENU
----
BREAKFAST
K&B's Pancake Breakfast 2.99
Pancakes with scrambled eggs, and toast
Blueberry Pancakes 3.49
Pancakes made with fresh blueberries, and blueberry syrup
Waffles 3.59
Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT 2.99
(Fakin') Bacon with lettuce & tomato on whole wheat
Steamed Veggies and Brown Rice 3.99
Steamed vegetables over brown rice
Pasta 3.89
Spaghetti with Marinara Sauce, and a slice of sourdough bread

Customer asks, is the Hotdog vegetarian?


Waitress says: No

Customer asks, are the Waffles vegetarian?


Waitress says: Yes
*/
[Link]:

import [Link];
public interface Menu
{
public Iterator createIterator();
}

[Link]:
public class MenuItem
{
String name;
String description;
boolean vegetarian;
double price;

public MenuItem(String name,String description,boolean vegetarian,double price)


{
[Link] = name;
[Link] = description;
[Link] = vegetarian;
[Link] = price;
}

public String getName()


{
return name;
}

public String getDescription()


{
return description;
}

public double getPrice()


{
return price;
}

public boolean isVegetarian()


{
return vegetarian;
}
}
[Link]:

import [Link];
public class DinerMenu implements Menu
{
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;

public DinerMenu()
{
menuItems = new MenuItem[MAX_ITEMS];

addItem("Vegetarian BLT","(Fakin') Bacon with lettuce & tomato on whole


wheat", true, 2.99);
addItem("BLT","Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day","Soup of the day, with a side of potato salad", false,
3.29);
addItem("Hotdog","A hot dog, with saurkraut, relish, onions, topped with
cheese",false, 3.05);
addItem("Steamed Veggies and Brown Rice","Steamed vegetables over brown
rice", true, 3.99);
addItem("Pasta","Spaghetti with Marinara Sauce, and a slice of sourdough
bread",true, 3.89);
}

public void addItem(String name, String description,boolean vegetarian, double price)


{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS)
{
[Link]("Sorry, menu is full! Can't add item to menu");
}
else
{
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}

public MenuItem[] getMenuItems()


{
return menuItems;
}

public Iterator createIterator()


{
return new DinerMenuIterator(menuItems);
}
}

[Link]:

import [Link];
public class DinerMenuIterator implements Iterator
{
MenuItem[] list;
int position = 0;

public DinerMenuIterator(MenuItem[] list)


{
[Link] = list;
}

public Object next()


{
MenuItem menuItem = list[position];
position = position + 1;
return menuItem;
}

public boolean hasNext()


{
if (position >= [Link] || list[position] == null)
{
return false;
}
else
{
return true;
}
}

public void remove()


{
if (position <= 0)
{
throw new IllegalStateException("You can't remove an item until you've
done at least one next()");
}
if (list[position-1] != null)
{
for (int i = position-1; i < ([Link]-1); i++)
{
list[i] = list[i+1];
}
list[[Link]-1] = null;
}
}
}

[Link]:

import [Link];
import [Link];
public class PancakeHouseMenu implements Menu
{
ArrayList menuItems;
public PancakeHouseMenu()
{
menuItems = new ArrayList();
addItem("K&B's Pancake Breakfast","Pancakes with scrambled eggs, and
toast",true,2.99);
addItem("Regular Pancake Breakfast","Pancakes with fried eggs,
sausage",false,2.99);
addItem("Blueberry Pancakes","Pancakes made with fresh blueberries, and
blueberry syrup",true,3.49);
addItem("Waffles","Waffles, with your choice of blueberries or
strawberries",true,3.59);
}

public void addItem(String name, String description,boolean vegetarian, double price)


{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
[Link](menuItem);
}

public ArrayList getMenuItems()


{
return menuItems;
}
public Iterator createIterator()
{
return [Link]();
}
}

[Link]:

import [Link];
public class Waitress
{
Menu pancakeHouseMenu;
Menu dinerMenu;

public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) {


[Link] = pancakeHouseMenu;
[Link] = dinerMenu;
}

public void printMenu() {


Iterator pancakeIterator = [Link]();
Iterator dinerIterator = [Link]();

[Link]("MENU\n----\nBREAKFAST");
printMenu(pancakeIterator);
[Link]("\nLUNCH");
printMenu(dinerIterator);
}

private void printMenu(Iterator iterator) {


while ([Link]()) {
MenuItem menuItem = (MenuItem)[Link]();
[Link]([Link]() + ", ");
[Link]([Link]() + " -- ");
[Link]([Link]());
}
}

public void printVegetarianMenu() {


[Link]("\nVEGETARIAN MENU\n----\nBREAKFAST");
printVegetarianMenu([Link]());
[Link]("\nLUNCH");
printVegetarianMenu([Link]());
}

public boolean isItemVegetarian(String name) {


Iterator pancakeIterator = [Link]();
if (isVegetarian(name, pancakeIterator)) {
return true;
}
Iterator dinerIterator = [Link]();
if (isVegetarian(name, dinerIterator)) {
return true;
}
return false;
}

private void printVegetarianMenu(Iterator iterator) {


while ([Link]()) {
MenuItem menuItem = (MenuItem)[Link]();
if ([Link]()) {
[Link]([Link]());
[Link]("\t\t" + [Link]());
[Link]("\t" + [Link]());
}
}
}

private boolean isVegetarian(String name, Iterator iterator) {


while ([Link]()) {
MenuItem menuItem = (MenuItem)[Link]();
if ([Link]().equals(name)) {
if ([Link]()) {
return true;
}
}
}
return false;
}
}
Practical 9
Write a Java Program to implement State Pattern for Gumball Machine. Create instance ariable
that holds current state from there, we just need to handle all actions, behaviors and state
transition that can happen. For actions we need to implement methods to insert a quarter,
remove a quarter, turning the crank and display gumball.

[Link]:

public class GumballMachineTestDrive


{
public static void main(String[] args)
{
GumballMachine gumballMachine = new GumballMachine(5);

[Link](gumballMachine);

[Link]();
[Link]();

[Link](gumballMachine);

[Link]();
[Link]();
[Link]();

[Link](gumballMachine);

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();

[Link](gumballMachine);

[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();

[Link](gumballMachine);
}
}

/*
Output:
Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

D:\MScSem3Practicals\SADP Pract Assignment\Pract9>java GumballMachineTestDrive

Mighty Gumball, Inc.


Java-enabled Standing Gumball Model #2004
Inventory: 5 gumballs
Machine is waiting for quarter

You inserted a quarter


You turned...
A gumball comes rolling out the slot

Mighty Gumball, Inc.


Java-enabled Standing Gumball Model #2004
Inventory: 4 gumballs
Machine is waiting for quarter

You inserted a quarter


Quarter returned
You turned but there's no quarter

Mighty Gumball, Inc.


Java-enabled Standing Gumball Model #2004
Inventory: 4 gumballs
Machine is waiting for quarter

You inserted a quarter


You turned...
A gumball comes rolling out the slot
You inserted a quarter
You turned...
A gumball comes rolling out the slot
You haven't inserted a quarter

Mighty Gumball, Inc.


Java-enabled Standing Gumball Model #2004
Inventory: 2 gumballs
Machine is waiting for quarter

You inserted a quarter


You can't insert another quarter
You turned...
A gumball comes rolling out the slot
You inserted a quarter
You turned...
A gumball comes rolling out the slot
Oops, out of gumballs!
You can't insert a quarter, the machine is sold out
You turned, but there are no gumballs

Mighty Gumball, Inc.


Java-enabled Standing Gumball Model #2004
Inventory: 0 gumballs
Machine is sold out

*/

[Link]:

public class GumballMachine


{
final static int SOLD_OUT = 0;
final static int NO_QUARTER = 1;
final static int HAS_QUARTER = 2;
final static int SOLD = 3;

int state = SOLD_OUT;


int count = 0;

public GumballMachine(int count)


{
[Link] = count;
if (count > 0)
{
state = NO_QUARTER;
}
}

public void insertQuarter()


{
if (state == HAS_QUARTER)
{
[Link]("You can't insert another quarter");
}
else if (state == NO_QUARTER)
{
state = HAS_QUARTER;
[Link]("You inserted a quarter");
}
else if (state == SOLD_OUT)
{
[Link]("You can't insert a quarter, the machine is sold out");
}
else if (state == SOLD)
{
[Link]("Please wait, we're already giving you a gumball");
}
}

public void ejectQuarter()


{
if (state == HAS_QUARTER)
{
[Link]("Quarter returned");
state = NO_QUARTER;
}
else if (state == NO_QUARTER)
{
[Link]("You haven't inserted a quarter");
}
else if (state == SOLD)
{
[Link]("Sorry, you already turned the crank");
}
else if (state == SOLD_OUT)
{
[Link]("You can't eject, you haven't inserted a quarter yet");
}
}
public void turnCrank()
{
if (state == SOLD)
{
[Link]("Turning twice doesn't get you another gumball!");
}
else if (state == NO_QUARTER)
{
[Link]("You turned but there's no quarter");
}
else if (state == SOLD_OUT)
{
[Link]("You turned, but there are no gumballs");
}
else if (state == HAS_QUARTER)
{
[Link]("You turned...");
state = SOLD;
dispense();
}
}

public void dispense()


{
if (state == SOLD)
{
[Link]("A gumball comes rolling out the slot");
count = count - 1;
if (count == 0)
{
[Link]("Oops, out of gumballs!");
state = SOLD_OUT;
}
else
{
state = NO_QUARTER;
}
}
else if (state == NO_QUARTER)
{
[Link]("You need to pay first");
}
else if (state == SOLD_OUT)
{
[Link]("No gumball dispensed");
}
else if (state == HAS_QUARTER)
{
[Link]("No gumball dispensed");
}
}

public void refill(int numGumBalls)


{
[Link] = numGumBalls;
state = NO_QUARTER;
}

public String toString()


{
StringBuffer result = new StringBuffer();
[Link]("\nMighty Gumball, Inc.");
[Link]("\nJava-enabled Standing Gumball Model #2004\n");
[Link]("Inventory: " + count + " gumball");
if (count != 1)
{
[Link]("s");
}
[Link]("\nMachine is ");
if (state == SOLD_OUT)
{
[Link]("sold out");
}
else if (state == NO_QUARTER)
{
[Link]("waiting for quarter");
}
else if (state == HAS_QUARTER)
{
[Link]("waiting for turn of crank");
}
else if (state == SOLD)
{
[Link]("delivering a gumball");
}
[Link]("\n");
return [Link]();
}
}
Practical 10
Write a java program to implement Adapter pattern to design Heart Model to Beat Model.

[Link]:

package djview;
import [Link].*;
public class HeartModel implements HeartModelInterface, Runnable
{
ArrayList beatObservers = new ArrayList();
ArrayList bpmObservers = new ArrayList();
int time = 1000;
int bpm = 90;
Random random = new Random([Link]());
Thread thread;
public HeartModel()
{
thread = new Thread(this);
[Link]();
}
public void run()
{
int lastrate = -1;
for(;;)
{
int change = [Link](10);
if ([Link](2) == 0)
{
change = 0 - change;
}
int rate = 60000/(time + change);
if (rate < 120 && rate > 50)
{
time += change;
notifyBeatObservers();
if (rate != lastrate)
{
lastrate = rate;
notifyBPMObservers();
}
}
try
{
[Link](time);
}
catch (Exception e)
{}
}
}
public int getHeartRate()
{
return 60000/time;
}
public void registerObserver(BeatObserver o)
{
[Link](o);
}
public void removeObserver(BeatObserver o)
{
int i = [Link](o);
if (i >= 0)
{
[Link](i);
}
}
public void notifyBeatObservers()
{
for(int i = 0; i < [Link](); i++)
{
BeatObserver observer = (BeatObserver)[Link](i);
[Link]();
}
}
public void registerObserver(BPMObserver o)
{
[Link](o);
}
public void removeObserver(BPMObserver o)
{
int i = [Link](o);
if (i >= 0)
{
[Link](i);
}
}
public void notifyBPMObservers()
{
for(int i = 0; i < [Link](); i++)
{
BPMObserver observer = (BPMObserver)[Link](i);
[Link]();
}
}
}

[Link]:

package djview;
import [Link].*;
import [Link].*;
public class BeatModel implements BeatModelInterface, MetaEventListener
{
Sequencer sequencer;
ArrayList beatObservers = new ArrayList();
ArrayList bpmObservers = new ArrayList();
int bpm = 90;
Sequence sequence;
Track track;
public void initialize()
{
setUpMidi();
buildTrackAndStart();
}
public void on()
{
[Link]();
setBPM(90);
}
public void off()
{
setBPM(0);
[Link]();
}
public void setBPM(int bpm)
{
[Link] = bpm;
[Link](getBPM());
notifyBPMObservers();
}

public int getBPM()


{
return bpm;
}

void beatEvent()
{
notifyBeatObservers();
}
public void registerObserver(BeatObserver o)
{
[Link](o);
}

public void notifyBeatObservers()


{
for(int i = 0; i < [Link](); i++)
{
BeatObserver observer = (BeatObserver)[Link](i);
[Link]();
}
}

public void registerObserver(BPMObserver o)


{
[Link](o);
}

public void notifyBPMObservers()


{
for(int i = 0; i < [Link](); i++)
{
BPMObserver observer = (BPMObserver)[Link](i);
[Link]();
}
}
public void removeObserver(BeatObserver o)
{
int i = [Link](o);
if (i >= 0)
{
[Link](i);
}
}
public void removeObserver(BPMObserver o)
{
int i = [Link](o);
if (i >= 0)
{
[Link](i);
}
}
public void meta(MetaMessage message)
{
if ([Link]() == 47)
{
beatEvent();
[Link]();
setBPM(getBPM());
}
}
public void setUpMidi()
{
try
{
sequencer = [Link]();
[Link]();
[Link](this);
sequence = new Sequence([Link],4);
track = [Link]();
[Link](getBPM());
}
catch(Exception e)
{
[Link]();
}
}
public void buildTrackAndStart()
{
int[] trackList = {35, 0, 46, 0};
[Link](null);
track = [Link]();
makeTracks(trackList);
[Link](makeEvent(192,9,1,0,4));
try
{
[Link](sequence);
}
catch(Exception e)
{
[Link]();
}
}

public void makeTracks(int[] list)


{
for (int i = 0; i < [Link]; i++)
{
int key = list[i];
if (key != 0)
{
[Link](makeEvent(144,9,key, 100, i));
[Link](makeEvent(128,9,key, 100, i+1));
}
}
}

public MidiEvent makeEvent(int comd, int chan, int one, int two, int tick)
{
MidiEvent event = null;
try
{
ShortMessage a = new ShortMessage();
[Link](comd, chan, one, two);
event = new MidiEvent(a, tick);

}
catch(Exception e)
{
[Link]();
}
return event;
}
}

[Link]:

package djview;
public class BeatController implements ControllerInterface
{
BeatModelInterface model;
DJView view;

public BeatController(BeatModelInterface model)


{
[Link] = model;
view = new DJView(this, model);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
}

public void start()


{
[Link]();
[Link]();
[Link]();
}

public void stop()


{
[Link]();
[Link]();
[Link]();
}

public void increaseBPM()


{
int bpm = [Link]();
[Link](bpm + 1);
}

public void decreaseBPM()


{
int bpm = [Link]();
[Link](bpm - 1);
}

public void setBPM(int bpm)


{
[Link](bpm);
}
}
[Link]:

package djview;
public class BeatBar extends JProgressBar implements Runnable
{
JProgressBar progressBar;
Thread thread;
public BeatBar()
{
thread = new Thread(this);
setMaximum(100);
[Link]();
}
public void run()
{
for(;;)
{
int value = getValue();
value = (int)(value * .75);
setValue(value);
repaint();
try
{
[Link](50);
}
catch (Exception e) {};
}
}
}

[Link]:

package djview;
public interface HeartModelInterface
{
int getHeartRate();
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}
[Link]:

package djview;
public interface BeatModelInterface
{
void initialize();
void on();
void off();
void setBPM(int bpm);
int getBPM();
void registerObserver(BeatObserver o);
void removeObserver(BeatObserver o);
void registerObserver(BPMObserver o);
void removeObserver(BPMObserver o);
}

[Link]:

package djview;
public interface ControllerInterface
{
void start();
void stop();
void increaseBPM();
void decreaseBPM();
void setBPM(int bpm);
}

[Link]

package djview;
public interface BPMObserver
{
void updateBPM();
}

[Link]:

package djview;
public interface BeatObserver
{
void updateBeat();
}
[Link]:

package djview;
public class HeartTestDrive
{
public static void main (String[] args)
{
HeartModel heartModel = new HeartModel();
ControllerInterface model = new HeartController(heartModel);
}
}

[Link]:

package djview;
public class DJTestDrive
{
public static void main (String[] args)
{
BeatModelInterface model = new BeatModel();
ControllerInterface controller = new BeatController(model);
}
}

Output:

Common questions

Powered by AI

The implementation of the Decorator pattern in the LowerCaseInputStream class is achieved by extending the FilterInputStream and overriding the read methods to transform input data. This pattern is significant in stream processing as it allows the behavior of input streams to be modified or extended dynamically without affecting existing code. LowerCaseInputStream adds the behavior of converting characters to lowercase on-the-fly while reading, thus offering a flexible way to transform input data streams. This demonstrates the pattern's strength in enhancing or modifying component functionalities in a non-intrusive manner .

Encapsulation in the ChocolateBoiler class is critical for implementing the Singleton pattern, as it restricts access to the single instance of ChocolateBoiler. By having a private static variable uniqueInstance and a private constructor, the class controls how and when an instance is created, ensuring that only one instance exists at any time. This encapsulation is crucial because it prevents other classes from instantiating the class directly, thereby preserving the Singleton property's integrity. Encapsulation also allows controlled access to the class's methods, maintaining correct state transitions in the chocolate boiling process .

The State Pattern in the GumballMachine class is applied by encapsulating individual states (such as SoldOutState, NoQuarterState, etc.) into separate classes that handle respective behavior. The gumball machine's current state is stored as an instance variable, and actions (insertQuarter, turnCrank) lead to state transitions handled by polymorphism. The benefit of this pattern is in managing complex state-dependent behaviors, simplifying the control logic by distributing it across the state classes. This makes the code more manageable, extendable, and adheres to the Open/Closed Principle by allowing new states or actions to be added with minimal changes to existing code .

The Factory Method pattern enhances the scalability of the PizzaStore application by delegating the creation logic of different pizza types to subclasses of PizzaStore, namely ChicagoPizzaStore and NYPizzaStore. When a new pizza type needs to be added, a developer can create a new subclass of Pizza or extend existing stores to add specific pizza creation methods without altering the existing code structure. This enables the application to grow and accommodate new requirements with minimal changes to existing code, adhering to Open/Closed Principle .

The Singleton pattern in multithreading environments, as used in the ChocolateBoiler, requires careful handling to avoid creating multiple instances in concurrent scenarios. The current implementation doesn't address thread safety, which may lead to multiple threads seeing a partially initialized instance. To remedy this, synchronization mechanisms like synchronized blocks or methods should be employed, or alternative approaches such as using an enum or Bill Pugh's singleton design could ensure thread safety. These improvements are crucial in maintaining the integrity of the singleton pattern across thread interactions .

The Adapter pattern in the EnumerationIterator is implemented by having the EnumerationIterator class take an Enumeration as a parameter and implementing the Iterator interface. This allows an Enumeration to be treated as an Iterator by providing the methods hasNext, next, and remove (where remove throws an UnsupportedOperationException since Enumeration doesn't support removing elements). The practical application scenario is to use this adapter when working with APIs or libraries that require an Iterator but you have an Enumeration, ensuring compatibility and reuse of existing code .

The PizzaFactoryDemo program uses the Factory Method design pattern. This pattern provides a way to decouple the creation of objects from their implementation, allowing the application to be flexible and scalable. By using the Factory Method, the program can create different types of pizzas, such as NY Style Cheese Pizza and Chicago Style Clam Pizza, without modifying the client code. This enhances the software architecture by promoting a separation of concerns and enabling easy extension of new pizza types .

The Strategy design pattern in the WeatherData application is evident in how different display elements such as CurrentConditionsDisplay, StatisticsDisplay, and ForecastDisplay query and update their data. Each display utilizes its own strategy to interpret the raw weather data provided by WeatherData, thus reflecting the current conditions, statistics, and forecast differently. This pattern provides flexibility by allowing changes or additions to the display strategies without altering the WeatherData class. Therefore, new display types can be added or existing ones modified without major changes to the overall architecture, making the system adaptable and easy to extend .

The use of the Command pattern in the CeilingFan classes encapsulates requests as objects, allowing operations like turning the fan on or off to be parameterized, queued, and logged. This pattern increases extendability by allowing new commands to be created without modifying existing ones, and enhances reusability by decoupling the object that invokes the operation from the one that performs it. As a result, the system can be extended to include new fan speeds or even other device controls without altering existing command structures, making it both flexible and adaptable .

Implementing the Iterator pattern in DinerMenu presents challenges such as ensuring a consistent interface across different menu collections and managing internal state without exposing the underlying structure. The DinerMenu addresses these issues by providing a DinerMenuIterator that abstracts the iteration mechanism, allowing traversal without knowledge of the internal representation (an array in this case). This pattern allows uniform access to different menu types like PancakeHouseMenu (which uses an ArrayList), thus facilitating operations over diverse collections without modifying client code .

Name: Tanmay Kolekar 
Subject: SADP Practical Sol​n​. 
Roll No.: 421 
 
 
Practical 1: 
Write a JAVA Program to implement bui
public WeatherData() 
 
{ 
 
observers = new ArrayList<>(); 
 
} 
 
public void registerObserver(Observer o) 
 
{ 
 
obse
public float getPressure() 
 
{ 
 
return pressure; 
 
} 
} 
 
ForecastDisplay.java: 
 
class ForecastDisplay implements Ob
class StatisticsDisplay implements Observer, DisplayElement 
{ 
 
private float maxTemp = 0.0f; 
 
private float minTemp =
{ 
 
this.weatherData = weatherData; 
 
 
weatherData.registerObserver(this); 
 
} 
 
 
public void update(float temperatur
Current conditions: 80.0F degrees and 65.0% humidity 
Avg/Max/Min temperature = 80.0/80.0/80.0 
Forecast: Improving weather o
Practical 2: 
Write a Java Program to implement I/O Decorator for converting uppercase letters to lower case 
letters. 
 
Low
System.out.print((char)c); 
} 
in.close(); 
} 
catch (IOException e) 
{ 
e.printStackTrace(); 
} 
} 
} 
 
/* 
Input: test.txt
Practical 3: 
Write a Java Program to implement Factory method for Pizza Store with createPizza(), 
orederPizza(), prepare(),
StringBuffer display = new StringBuffer(); 
display.append("---- " + name + " ----
"); 
display.append(dough + "
"); 
displ

You might also like