0% found this document useful (0 votes)
82 views39 pages

SADP

The document describes programs to implement various design patterns in Java. 1. It includes a program to implement the Observer pattern to create a weather station app with observers like a forecast display and heat index display that update when the weather data changes. 2. A program to implement the Decorator pattern to convert uppercase letters in a text file to lowercase. 3. A program to implement the Factory pattern to create different types of pizza (e.g. cheese, pepperoni) using a pizza store factory class. The pizza classes all implement common prepare, bake, cut and box methods.

Uploaded by

tina
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)
82 views39 pages

SADP

The document describes programs to implement various design patterns in Java. 1. It includes a program to implement the Observer pattern to create a weather station app with observers like a forecast display and heat index display that update when the weather data changes. 2. A program to implement the Decorator pattern to convert uppercase letters in a text file to lowercase. 3. A program to implement the Factory pattern to create different types of pizza (e.g. cheese, pepperoni) using a pizza store factory class. The pizza classes all implement common prepare, bake, cut and box methods.

Uploaded by

tina
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

Index

[Link] Program

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()

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

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

4 Write a Java Program to implement Singleton pattern for multithreading.

5 Write a Java Program to implement command pattern to test Remote Control.

6 Write a Java Program to implement undo command to test Ceiling fan.

7 Write a Java Program to implement Adapter pattern for Enumeration iterator.

8 Write a Java Program to implement Iterator Pattern for Designing Menu like Breakfast, Lunch or
Dinner Menu.
Q1) Write a JAVA Program to implement built-in support
([Link]) Weather station with members temperature,
humidity, pressure and methods mesurmentsChanged(),
setMesurment(), getTemperature(), getHumidity(), getPressure()

public interface Observer


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

public interface DisplayElement


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

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;
}
}

public 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");
}
}
}
public class HeatIndexDisplay implements Observer, DisplayElement
{
float heatIndex = 0.0f;
private WeatherData weatherData;

public HeatIndexDisplay(WeatherData weatherData)


{
[Link] = weatherData;
[Link](this);
}
public void update(float t, float rh, float pressure)
{
heatIndex = computeHeatIndex(t, rh);
display();
}

private float computeHeatIndex(float t, float rh)


{
float index = (float)((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh)
+ (0.00941695 * (t * t)) + (0.00728898 * (rh * rh))
+ (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) +
(0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 *
(rh * rh * rh)) + (0.00000142721 * (t * t * t * rh)) +
(0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) +
0.000000000843296 * (t * t * rh * rh * rh)) -
(0.0000000000481975 * (t * t * t * rh * rh * rh)));
return index;
}

public void display()


{
[Link]("Heat index is " + heatIndex);
}
}

Step 6: Create third Observer StatisticsDisplay class.

public 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);
}
}
public 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");
}
}
public 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

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
Q2. Write a Java Program to implement I/O Decorator for converting
uppercase letters to lower case letters.

import [Link].*;
import [Link].*;

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;
}
}
public class Main
{
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]();
}
}
}
Q3) 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.

import [Link];

abstract public class Pizza {


String name;
String dough;
String sauce;
ArrayList toppings = new ArrayList();

public String getName() {


return name;
}

public void prepare() {


[Link]("Preparing " + name);
}

public void bake() {


[Link]("Baking " + name);
}

public void cut() {


[Link]("Cutting " + name);
}

public void box() {


[Link]("Boxing " + name);
}

public String toString() {


// code to display pizza name and ingredients
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]();
}
}

Step 2: Create Concrete Pizza classes which extends abstract Pizza class
- CheesePizza, ClamPizza, VeggiePizza, and PepperoniPizza class:

public class CheesePizza extends Pizza {


public CheesePizza() {
name = "Cheese Pizza";
dough = "Regular Crust";
sauce = "Marinara Pizza Sauce";
[Link]("Fresh Mozzarella");
[Link]("Parmesan");
}
}

public class ClamPizza extends Pizza {


public ClamPizza() {
name = "Clam Pizza";
dough = "Thin crust";
sauce = "White garlic sauce";
[Link]("Clams");
[Link]("Grated parmesan cheese");
}
}

public class VeggiePizza extends Pizza {


public VeggiePizza() {
name = "Veggie Pizza";
dough = "Crust";
sauce = "Marinara sauce";
[Link]("Shredded mozzarella");
[Link]("Grated parmesan");
[Link]("Diced onion");
[Link]("Sliced mushrooms");
[Link]("Sliced red pepper");
[Link]("Sliced black olives");
}
}

public class PepperoniPizza extends Pizza {


public PepperoniPizza() {
name = "Pepperoni Pizza";
dough = "Crust";
sauce = "Marinara sauce";
[Link]("Sliced Pepperoni");
[Link]("Sliced Onion");
[Link]("Grated parmesan cheese");
}
}

Step 3: Create a SimplePizzaFactory class which produces pizza object


based on the type of the pizza - SimplePizzaFactory java class.

public class SimplePizzaFactory {

public Pizza createPizza(String type) {


Pizza pizza = null;

if ([Link]("cheese")) {
pizza = new CheesePizza();
} else if ([Link]("pepperoni")) {
pizza = new PepperoniPizza();
} else if ([Link]("clam")) {
pizza = new ClamPizza();
} else if ([Link]("veggie")) {
pizza = new VeggiePizza();
}
return pizza;
}
}

Step 4: Let's create PizzaStore to order the Pizza:

package [Link];

public class PizzaStore {


SimplePizzaFactory factory;

public PizzaStore(SimplePizzaFactory factory) {


[Link] = factory;
}

public Pizza orderPizza(String type) {


Pizza pizza;
pizza = [Link](type);

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

return pizza;
}
}

Step 5: Let's test the Factory Pattern with below PizzaTestDrive:

public class PizzaTestDrive {

public static void main(String[] args) {


SimplePizzaFactory factory = new SimplePizzaFactory();
PizzaStore store = new PizzaStore(factory);

Pizza pizza = [Link]("cheese");


[Link]("We ordered a " + [Link]() + "\n");

pizza = [Link]("veggie");
[Link]("We ordered a " + [Link]() + "\n");
}
}

Output :
Preparing Cheese Pizza
Baking Cheese Pizza
Cutting Cheese Pizza
Boxing Cheese Pizza
We ordered a Cheese Pizza

Preparing Veggie Pizza


Baking Veggie Pizza
Cutting Veggie Pizza
Boxing Veggie Pizza
We ordered a Veggie Pizza
Q4. Write a Java Program to implement Singleton pattern for
multithreading

package [Link];

public class SingletonDesignPatternInMultiThreadedEnvironment


{
private static volatile
SingletonDesignPatternInMultiThreadedEnvironment INSTANCE;

private SingletonDesignPatternInMultiThreadedEnvironment()
{}
public static SingletonDesignPatternInMultiThreadedEnvironment
getInstance()
{
synchronized
([Link])
{
if(null == INSTANCE)
{
INSTANCE =new SingletonDesignPatternInMultiThreadedEnvironment();
}
return INSTANCE;
}
}
}

Output

LazySingleton was created 0 ms ago


EagerSingleton was created 1001 ms ago
Q5. Write a Java Program to implement command pattern to test
Remote Control.

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]();
}

class RemoteControlTest
{
public static void main(String[] args)
{
SimpleRemoteControl remote =new SimpleRemoteControl();

Light light = new Light();

Stereo stereo = new Stereo();

[Link](newLightOnCommand(light));
[Link]();

[Link](newStereoOnWithCDCommand(stereo));
[Link]();

[Link](newStereoOffCommand(stereo));
[Link]();
}
}

Output

Light is on
Stereo is on
Stereo is set for CD input
Stereo volume set to 11
Stereo is off
Q6. Write a Java Program to implement undo command to test Ceiling
fan.

interface Command
{
public void execute();
}

class CeilingFan
{
public void on()
{
[Link]("Ceiling Fan is on");
}
public void off()
{
[Link]("Ceiling Fan is off");
}
}

class CeilingFanOnCommand implements Command


{
CeilingFan c;

public CeilingFanOnCommand(CeilingFan l)
{
this.c = l;
}

public void execute() {


[Link]();
}}
class CeilingFanOffCommand implements Command
{
CeilingFan c;

public CeilingFanOffCommand(CeilingFan l)
{
this.c = l;
}
public void execute()
{
[Link]();
}
}

class SimpleRemoteControl
{
Command slot;

public SimpleRemoteControl() {}

public void setCommand(Command command)


{
slot = command;
}

public void buttonWasPressed()


{
[Link]();
}

}
public class Main
{
public static void main(String[] args)
{
SimpleRemoteControl remote = new SimpleRemoteControl();

CeilingFan ceilingFan=new CeilingFan();

CeilingFanOnCommand ceilingFanOn =new CeilingFanOnCommand(ceilingFan);

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

CeilingFanOffCommand ceilingFanOff =new CeilingFanOffCommand(ceilingFan);

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

}
}

Output

Ceiling Fan is on
Ceiling Fan is off
Q7. Write a Java Program to implement Adapter pattern for
Enumeration iterator

import [Link].*;

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();
}
}
public class Main
{
public static void main (String args[])
{
Vector v = new Vector([Link](args));
Iterator iterator = new EnumerationIterator([Link]());
while ([Link]())
{
[Link]([Link]());
}
}
}
Q8) Write a Java Program to implement Iterator Pattern for Designing
Menu like Breakfast, Lunch or Dinner Menu.
import [Link];

public interface Menu {

public Iterator<?> createIterator();

String name;

public String getName() {

return name;

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;
}

public class PancakeHouseMenu implements Menu

ArrayList<MenuItem> menuItems;

public PancakeHouseMenu()

name = "BREAKFAST";

menuItems = new ArrayList<MenuItem>();

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<MenuItem> getMenuItems()

return menuItems;

}
public Iterator<MenuItem> createIterator()

return [Link]();

// other menu methods here

import [Link];

public class DinerMenu implements Menu


{
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;

public DinerMenu()
{
name = "LUNCH";
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<MenuItem> createIterator()


{
return new DinerMenuIterator(menuItems);
//return new AlternatingDinerMenuIterator(menuItems);
}

public
// other menu methods here
}

Also DinerMenu returns its concrete implementation of the


Iterator<MenuItem> interface, DinerMenuIterator:

import [Link];

public class DinerMenuIterator implements Iterator<MenuItem>


{
MenuItem[] list;
int position = 0;

public DinerMenuIterator(MenuItem[] list)


{
[Link] = list;
}

public MenuItem 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;
}
}
}

public class Waitress


{
ArrayList<Menu> menus;

public Waitress(ArrayList<Menu> menus) {


[Link] = menus;
}

public void printMenu()


{
Iterator<?> menuIterator = [Link]();

[Link](MENU\n----\n);
while([Link]()) {
Menu menu = (Menu)[Link]();
[Link]("\n" + [Link]() + "\n");
printMenu([Link]());
}
}

void printMenu(Iterator<?> iterator)


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

To test this program we use the following snippet:

public class MenuTestDrive


{
public static void main(String args[]) {
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu();
ArrayList<Menu> menus = new ArrayList<Menu>();
[Link](pancakeHouseMenu);
[Link](dinerMenu);
Waitress waitress = new Waitress(menus);
[Link]();

}
}
The output printing the menus is:

$ 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

You might also like