Download File

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Software Design Laboratory
Sub. Code 10MCA56
Program 1. Publishers-Subscriber / Observer Design Pattern
Intent:
The Observer Pattern defines one-to-many dependency between objects so that when one
object changes state; all its dependents are notified and updated automatically.
Design a Weather Information system.
The weather Station will be broadcasting the current weather conditions like temperature,
humidity and biometric pressure. Create an application which receives the weather
conditions and displays them in different forms. (i.e. displaying the current weather
conditions, displaying weather statistics). All displays will be updating the weather
conditions in real time, as and when the new conditions are recorded.
The concrete Subject: Weather Data
Concrete Observer: Current Display, Forecast Display
Pattern Instance:
Page | 1
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Class Diagram:
Use Case Diagram:
Page | 2
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Activity Diagram:
Page | 3
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Java Code:
WeatherData.java:
import java.util.Observable;
public class WeatherData extends Observable
{
public static void main(String a[])
{
WeatherData weatherData= new WeatherData();
CurrentDisplay cd=new CurrentDisplay(weatherData);
ForecastDisplay fd=new ForecastDisplay(weatherData);
weatherData.SetMeasurements(80f,65f,30.6f);
weatherData.SetMeasurements(82f,60f,29.5f);
weatherData.SetMeasurements(78f,90f,29.2f);
}
private float temperature;
public float getTemperature()
{
return temperature;
}
public void setTemperature(float theTemperature)
{
temperature = theTemperature;
}
private float pressure;
public float getPressure()
{
return pressure;
}
public void setPressure(float thePressure)
{
pressure = thePressure;
}
private float humidity;
public float getHumidity()
{
return humidity;
}
public void setHumidity(float theHumidity)
Page | 4
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
humidity = theHumidity;
}
public WeatherData()
{
}
public void SetMeasurements(float f, float h, float p)
{
this.temperature=f;
this.humidity=h;
this.pressure=p;
MeasurementsChanged();
}
public void MeasurementsChanged()
{
setChanged();
notifyObservers();
}
public void Notify()
{
}
}
CurrentDisplay.java:
import java.util.Observable;
import java.util.Observer;
public class CurrentDisplay implements Observer
{
private float temperature;
public float getTemperature()
{
return temperature;
}
public void setTemperature(float theTemperature)
{
temperature = theTemperature;
}
private float pressure;
Page | 5
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
public float getPressure()
{
return pressure;
}
public void setPressure(float thePressure)
{
pressure = thePressure;
}
private float humidity;
public float getHumidity()
{
return humidity;
}
public void setHumidity(float theHumidity)
{
humidity = theHumidity;
}
private Object observable;
public CurrentDisplay(Observable observable)
{
this.observable=observable;
observable.addObserver(this);
}
public Object getObservable()
{
return observable;
}
public void setObservable(Object theObservable)
{
observable = theObservable;
}
public CurrentDisplay()
{
}
public void Update(Observable obs,Object arg)
{
WeatherData wd=(WeatherData)obs;
this.temperature=wd.getTemperature();
this.humidity=wd.getHumidity();
this.pressure=wd.getPressure();
Page | 6
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Display();
}
public void Display()
{
System.out.println("Current
COndition"+temperature+"Fand"+humidity+"%humdity");
}
public void update(Observable o, Object arg)
{
WeatherData wd=(WeatherData)o;
this.temperature=wd.getTemperature();
this.humidity=wd.getHumidity();
this.pressure=wd.getPressure();
Display();
}
}
ForecastDisplay.java:
import java.util.Observable;
import java.util.Observer;
public class ForecastDisplay implements Observer
{
private float CurrentPressure=30.52f;
Observable observable;
public ForecastDisplay(Observable observable)
{
this.observable=observable;
observable.addObserver(this);
}
public float getCurrentPressure()
{
return CurrentPressure;
}
public void setCurrentPressure(float theCurrentPressure)
{
CurrentPressure = theCurrentPressure;
}
Page | 7
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
private float LastPressure;
public float getLastPressure()
{
return LastPressure;
}
public void setLastPressure(float theLastPressure)
{
LastPressure = theLastPressure;
}
public void Update(Observable o, Object arg)
{
if(o instanceof WeatherData)
{
WeatherData wd=(WeatherData)o;
LastPressure=CurrentPressure;
CurrentPressure=wd.getPressure();
Display();
}
}
public void Display()
{
System.out.println("Weather Forecadt");
if(CurrentPressure>LastPressure)
System.out.println("Weather Conditions Are Improving.");
else if(CurrentPressure==LastPressure)
System.out.println("Weather Conditions Are The Same.");
else
System.out.println("Weather Out Of Control.");
}
public void update(Observable o, Object arg)
{
if(o instanceof WeatherData)
{
WeatherData wd=(WeatherData)o;
LastPressure=CurrentPressure;
CurrentPressure=wd.getPressure();
Display();
}
}
}
Page | 8
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Output:
Page | 9
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 2. Command Design Pattern
Intent: Encapsulate a request as an object, thereby letting you parameterize clients with
different requests, queue or log requests, and support undoable operations.
Applicability:
Use the command design pattern when we want to:
1 Implement a callback functionality.
2 Specify, queue, and execute requests at different times.
3 Support undo and change operation.
4 Structure a system around high-level operations built on primitives operations.
Participants:
Command declares and interface for executing an operation
ConcreteCommand defines a binding between a Receiver object and an action. Implements
Execute by invoking the corresponding Operation(s) on Receiver.
Client creates a ConcreteCommand object and sets its receiver.
Invoker asks the command to carry out the request.
Receiver knows how to perform the operations associated with carrying out a request. Any
class may serve as a receiver.
Structure:
Page | 10
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Discussion:
The command pattern is a design pattern in which an object is used to represent and
encapsulate all the information needed to call a method at a later time.
Three terms always associated with the command pattern are client, invoker and receiver. The
client instantiates the command object and provides the information required to call the
method at a later time. The invoker decides when the method should be called. The receiver is
an instance of the class that contains the method's code.
Example:
Consider a simple switch. In this example we configure the Switch with 2 commands: to
turn the light on and to turn the light off.
A benefit of this particular implementation of the command Pattern is that the switch can be
used with any device, not just a light - the Switch in the following example turns a light on
and off, but the Switch's constructor is able to accept any subclasses of Command for its 2
parameters. For example, you could configure the Switch to start an engine.
Pattern Instance:
Page | 11
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Class Diagram:
Page | 12
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Java Code:
Light.java:
public class Light
{
String location = "";
public Light(String location)
{
this.location = location;
}
public void on()
{
System.out.println(location + " Light Is On.");
}
public void off() {
System.out.println(location + " Light Is Off.");
}
}
LightOffCommand.java:
public class LightOffCommand implements Command
{
Light light;
public LightOffCommand(Light light)
{
this.light = light;
}
public void execute()
{
light.off();
}
}
LightOnCommand.java:
public class LightOnCommand implements Command
{
Light light;
public LightOnCommand(Light light)
{
this.light = light;
}
public void execute()
{
Page | 13
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
light.on();
}
}
RemoteLoader.java:
public class RemoteLoader
{
public static void main(String[] args)
{
RemoteControl remoteControl = new RemoteControl();
Light livingRoomLight = new Light("Living Room");
Light kitchenLight = new Light("Kitchen");
LightOnCommand livingRoomLightOn =
new LightOnCommand(livingRoomLight);
LightOffCommand livingRoomLightOff =
new LightOffCommand(livingRoomLight);
LightOnCommand kitchenLightOn =
new LightOnCommand(kitchenLight);
LightOffCommand kitchenLightOff =
new LightOffCommand(kitchenLight);
remoteControl.setCommand(0, livingRoomLightOn, livingRoomLightOff);
remoteControl.setCommand(1, kitchenLightOn, kitchenLightOff);
System.out.println(remoteControl);
remoteControl.onButtonWasPushed(0);
remoteControl.offButtonWasPushed(0);
remoteControl.onButtonWasPushed(1);
remoteControl.offButtonWasPushed(1);
}
}
RemoteControl.java:
public class RemoteControl
{
Command[] onCommands;
Command[] offCommands;
public RemoteControl()
{
onCommands = new Command[3];
offCommands = new Command[3];
}
public void setCommand(int slot, Command onCommand, Command offCommand)
Page | 14
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot)
{
onCommands[slot].execute();
}
public void offButtonWasPushed(int slot)
{
offCommands[slot].execute();
}
}
Command.java:
public interface Command
{
public void execute();
}
Output:
Page | 15
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 3. Forwarder Receiver Design Pattern
Context: Peer-to-Peer communication.
Problem: A common way to build distributed applications is to make use of available lowlevel mechanisms for inter-process communication (IPC) such as TCP/IP sockets or message
queues. These low-level mechanisms, however, often introduce dependencies on the
underlying operating system and network protocols.
The Forwarder-Receiver pattern is useful when you need to balance the following
forces;
a The system should allow the exchangeability of the communication
mechanisms.
b The cooperation of components follows a peer-to-peer model, in which a
sender only needs to know the names of its receivers.
c The communication between peers should not have a major impact on
performance.
Solution: Distributed peers collaborate to solve a problem. A peer may act as a client,
requesting services, as a server, providing services, or both. The details of the underlying
IPC mechanism for sending or receiving messages are hidden from the peers by
encapsulating all system-specific functionality into separate components.
Structure: The Forwarder-Receiver design pattern consists of three kinds of components,
forwarders, receivers and peers. Peer components are responsible for application tasks. To
carry out their tasks peers need to communicate with other peers. These may be located in a
different process, or even on a different machine.
Each peer knows the names of the remote peers with which it needs to
communicate. It uses a forwarder to send messages to other peers and a receive to receive
messages from other peers.
Participants and Responsibilities:
Server: - Agents running on the network nodes. They continuously monitor network events
and resources and listen for incoming messages from remote agents.
Forwarder:- Send messages across process boundaries. A forwarder provides a general
interface that is an abstraction of a particular IPC mechanism, and includes functionality for
marshaling and delivery of messages.
Receiver:- Are responsible for receiving messages. A receiver offers a general interface that
is an abstraction of a particular IPC mechanism. It includes functionality for receiving and
unmarshaling messages.
Page | 16
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Pattern Instance:
Class Diagram:
Page | 17
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Use Case Diagram:
Activity Diagram:
Page | 18
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Java Code:
Peer.java:
public class Peer
{
public Receiver receiver;
String name;
public Peer(String string)
{
name=string;
}
public Receiver getReceiver()
{
return receiver;
}
public void setReceiver(Receiver theReceiver)
{
receiver = theReceiver;
}
public Forwarder forwarder;
public Forwarder getForwarder()
{
return forwarder;
}
public void setForwarder(Forwarder theForwarder)
{
forwarder = theForwarder;
}
public void service(String msg,Peer dest)
{
System.out.println("Sending Msg: "+ dest);
System.out.println("Msg: "+msg);
this.forwarder.sendMsg(msg, dest, this);
}
public static void main(String args[])
{
Forwarder f1=new Forwarder();
Forwarder f2=new Forwarder();
Receiver r1=new Receiver();
Receiver r2=new Receiver();
Peer p1=new Peer("Peer1");
p1.setForwarder(f1);
Page | 19
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
p1.setReceiver(r1);
Peer p2=new Peer("Peer2");
p2.setForwarder(f2);
p2.setReceiver(r2);
p1.service("Its Peer2", p2);
}
}
Forwarder.java:
public class Forwarder
{
public Peer peer;
public Peer getPeer()
{
return peer;
}
public void setPeer(Peer thePeer)
{
peer = thePeer;
}
public Receiver receiver;
public Receiver getReceiver()
{
return receiver;
}
public void setReceiver(Receiver theReceiver)
{
receiver = theReceiver;
}
public void marshal()
{
}
public void deliver()
{
}
public void sendMsg(String msg,Peer dest,Peer src)
{
Receiver r=dest.getReceiver();
r.receiveMsg(msg,src);
}
Page | 20
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
}
Receiver.java:
public class Receiver
{
public Peer peer;
public Peer getPeer()
{
return peer;
}
public void setPeer(Peer thePeer)
{
peer = thePeer;
}
public Forwarder forwarder;
public Forwarder getForwarder()
{
return forwarder;
}
public void setForwarder(Forwarder theForwarder)
{
forwarder = theForwarder;
}
public void receive()
{
}
public void unmarshal()
{
}
public void receiveMsg(String m,Peer src)
{
System.out.println("msg received: "+src);
System.out.println("msg: "+m);
}
public void IPCmsg()
{
}
}
Page | 21
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Output:
Page | 22
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 4. Client-Dispatcher-Server Design Pattern
Intent: The Client-Dispatcher-Server design pattern introduces an intermediate layer
between clients and servers, the dispatcher component. It provides location transparency by
means of a name service, and hides the details of the establishment of the communication
connection between clients and servers.
Problem: When a software system uses servers distributed over a network it must provide a
means for communication between them. In many cases a connection between components
may have to be established before the communication can take place, depending on the
available communication facilities. Clients should not need to know where servers are
located.
Solution: Provide a dispatcher component to act as an intermediate layer between clients
and servers. The dispatcher implements a name service that allows clients to refer to servers
by names instead of physical locations, thus providing location transparency. In addition,
the dispatcher is responsible for establishing the communication channel between a client
and a server. Each server is uniquely identified by its name and is connected to clients by the
dispatcher.
The Client: The task of a client is to perform domain-specific tasks. The client accesses
operations offered by servers in order to carry out its processing tasks. Before sending a
request to a server, the client asks the dispatcher for a communication channel. The client
uses this channel to communicate with the server.
The Server: A server provides a set of operations to clients. It either registers itself or is
registered with the dispatcher by its name and address. A server component may be located
on the same computer as a client, or may be reachable via a network.
The Dispatcher: The dispatcher offers functionality for establishing communication
channels between clients and servers. To do this, it takes the name of a server component
and maps this name to the physical location of the server component. The dispatcher
establishes a communication link to the server using the available communication
mechanism and returns a communication handle to the client. If the dispatcher cannot
initiate a communication link with the requested server, it informs the client about the error
it encountered.
Page | 23
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Pattern Instance:
Class Diagram:
Page | 24
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Use Case Diagram:
Activity Diagram:
Java Code:
Page | 25
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
CDS.java:
public class CDS
{
public static Dispatcher disp=new Dispatcher();
public static void main(String args[])
{
Service s1=new PrintService("PrintS1","srv1");
Service s2=new PrintService("PrintS2","srv2");
Client c=new Client();
c.doTask();
}
}
Client.java:
public class Client
{
public PrintService printService;
public PrintService getPrintService()
{
return printService;
}
public void setPrintService(PrintService ps)
{
printService=ps;
}
public Dispatcher dispatcher;
public void setDispatcher(Dispatcher dp)
{
dispatcher=dp;
}
public void doTask()
{
Service s;
try
{
s=CDS.disp.locateServer("PrintS2");
s.runService();
Page | 26
}
catch(NotFound n)
{
System.out.println("The Requested Service is not available");
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
}
try
{
s=CDS.disp.locateServer("PrintS1");
s.runService();
}
catch(NotFound n)
{
System.out.println("The Requested Service is not available");
}
try
{
s=CDS.disp.locateServer("PrintS3");
s.runService();
}
catch(NotFound n)
{
System.out.println("The Requested Service is not available");
}
}
public void sendRequest()
{
}
}
Dispatcher.java:
import java.util.*;
import java.io.*;
class NotFound extends Exception {}
class Dispatcher
{
private Client client;
private PrintService printservice;
Hashtable registry=new Hashtable(123456);
public void registerService(String svc,Service obj)
{
Vector v=(Vector)registry.get(svc);
if(v==null)
Page | 27
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
v=new Vector();
registry.put(svc,v);
}v.addElement(obj);
}
public void unregisterService()
{}
Random rnd=new Random();
public Service locateServer(String svc)throws NotFound
{
Vector v=(Vector)registry.get(svc);
if(v==null) throw new NotFound();
int i=rnd.nextInt()%v.size();
return(Service)v.elementAt(i);
}
}
Server.java:
class PrintService extends Service
{
private Dispatcher dispatcher;
private Client client;
public PrintService(String svc,String srv)
{
super(svc,srv);
}
public void acceptConnection()
{}
public void runService()
{
System.out.println("Service"+nameofservice+" by "+nameofserver);
}
}
Service.java:
Page | 28
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
public abstract class Service
{
String nameofservice;
String nameofserver;
public Service(String svc,String srv)
{
nameofservice=svc;
nameofserver=srv;
CDS.disp.registerService(nameofservice,this);
}
abstract public void runService();
}
Output:
Page | 29
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 5. Proxy Design Pattern
Intent: Provide a surrogate or placeholder for another object to control access to it
Motivation:
1. A proxy is
-a person authorized to act for another person
-an agent or substitute
-the authority to act for another
2. There are situations in which a client does not or can not reference an object directly, but
wants to still interact with the object
3. A proxy object can act as the intermediary between the client and the target object
The proxy object has the same interface as the target object
The proxy holds a reference to the target object and can forward requests to the target as
required (delegation!)
In effect, the proxy object has the authority the act on behalf of the client to interact with the
target object
Applicability: Proxies are useful wherever there is a need for a more sophisticated
reference to a object than a simple pointer or simple reference can provide
Structure:
Page | 30
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Collaboration:
Example: Proxy
Imagine that we are creating an Application that is making use of email-service such as send
and receive email.. Assuming that the Client Application won't be always accessing the
Email Service, the Email Service is an ideal candidate to be modeled as a Virtual Proxy.
Pattern Instance:
Page | 31
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Class Diagram:
Page | 32
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Java Code:
Application.java:
public class Application
{
private ProxyEmailService proxyemailservice;
public ProxyEmailService getProxyemailservice()
{
return proxyemailservice;
}
public void setProxyemailservice(ProxyEmailService theProxyemailservice)
{
proxyemailservice = theProxyemailservice;
}
private ApplicationClient applicationclient;
public ApplicationClient getApplicationclient()
{
return applicationclient;
}
public void setApplicationclient(ApplicationClient theApplicationclient)
{
applicationclient = theApplicationclient;
}
public EmailService locateEmailService()
{
EmailService es=new ProxyEmailService();
return es;
}
}
Page | 33
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
ApplicationClient.java:
public class ApplicationClient
{
public Application getApplication()
{
return application;
}
public void setApplication(Application theApplication)
{
application = theApplication;
}
public static void main(String args[])
{
Application application=new Application();
EmailService emailService=application.locateEmailService();
emailService.sendMail("[email protected]","Hello mona","a text mail to say u
r selected");
emailService.receiveMail("[email protected]");
}
}
EmailService.java:
public interface EmailService {
public void sendMail(String receive,String subject,String text);
public void receiveMail(String receive);
}
Page | 34
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
ProxyEmailService.java:
public class ProxyEmailService implements EmailService
{
public ProxyEmailService()
{
}
private RealEmailService realSubject;
public RealEmailService getRealSubject()
{
return realSubject;
}
public void setRealSubject(RealEmailService theRealSubject)
{
realSubject = theRealSubject;
}
private RealEmailService enailService;
public RealEmailService getEnailService()
{
return enailService;
}
public void setEnailService(RealEmailService theEnailService)
{
enailService = theEnailService;
}
private Application application;
public Application getApplication()
{
return application;
}
public void setApplication(Application theApplication)
{
application = theApplication;
}
public ProxyEmailService(RealEmailService realSubject)
{
this.realSubject = realSubject;
}
private RealEmailService emailservice;
public void receiveMail(String receive)
Page | 35
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
if(emailservice==null)
{
emailservice=new RealEmailService();
}
emailservice.receiveMail(receive);
}
public void sendMail(String receive,String subject,String text)
{
if(emailservice==null)
{
emailservice=new RealEmailService();
}
emailservice.sendMail(receive,subject,text);
}
}
RealEmailService.java:
public class RealEmailService implements EmailService
{
public void sendMail(String receive,String subject,String text)
{
System.out.println("Sending Mail to '"+receive+"' with subject '"+subject+"'
and message is '"+text+"'");
}
public void receiveMail(String receive)
{
System.out.println("Receiving mail from '"+receive+"'");
}
}
Page | 36
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Output:
Page | 37
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 6. Whole Part (Composite) Design Pattern
Introduction




Sometimes called Composite
Helps with the aggregation of components (parts) that together form a semantic unit
(whole).
Direct access to the Parts is not possible
Compose objects into tree structures to represent part-whole hierarchies.

Whole-Part lets clients treat individual objects and compositions of object uniformly
Component




Declares the interface for objects in the Whole.
Implements default behavior for the interface common to all classes, as appropriate.
Declares an interface for accessing and managing its child components
Defines an interface for accessing a component’s parent in the recursive structure,
and implements it if that is appropriate.
Leaf
 Represents leaf objects in the Whole. A leaf has no children.
 Defines behavior for primitive objects in the Whole.
Composite
 Defines behavior for components having children.
 Stores child components.
 Implements child-related operations in the Component interface.
Client
 Manipulates objects in the Whole through the Whole interface.
Page | 38
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Pattern Instance:(Composite)
Class Diagram:
Java Code:
Application.java:
import java.util.*;
public class Application
{
public Application()
{
}
public static void main(String[] args)
{
List items = new ArrayList();
items.add(new ColdDrink("Pepsi","cold drink",10));
items.add(new ColdDrink("Coke","cold drink",20));
items.add(new ColdDrink("maza","cold drink",15));
Page | 39
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
ColdDrinkFamilyPack familyPack =
new ColdDrinkFamilyPack(items);
System.out.println("Discount for FamilyPack is");
System.out.println(familyPack.getPrice());
List item2s = new ArrayList();
item2s.add(new ColdDrink("Pepsi","cold drink",10));
item2s.add(new ColdDrink("Coke","cold drink",20));
item2s.add(new ColdDrink("maza","cold drink",15));
item2s.add(new ColdDrink("Pepsi","cold drink",10));
item2s.add(new ColdDrink("Coke","cold drink",20));
item2s.add(new ColdDrink("maza","cold drink",15));
ColdDrinkPartyPack partyPack =
new ColdDrinkPartyPack(item2s);
System.out.println("Discount for PartyPack is");
System.out.println(partyPack.getPrice());
}
}
ColdDrink.Java
public class ColdDrink implements Item
{
private String itemName;
private String iemDesc;
private double price;
public ColdDrink(String itemName, String desc, double price)
{
this.itemName=itemName;
this.iemDesc= desc;
this.price = price;
}
public double getPrice()
{
return price;
}
public String getItemName()
{
return itemName;
}
public String getIemDesc()
{
return iemDesc;
}
}
Page | 40
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
ColdDrinkFamilyPack.Java
import java.util.List;
public class ColdDrinkFamilyPack extends Composite
{
public ColdDrinkFamilyPack(List items)
{
super.addAll(items);
}
public double getPrice()
{
return super.getPrice() - super.getPrice()*.15; // get 15% discount on family
pack
}
}
ColdDrinkPartyPack.Java
import java.util.List;
public class ColdDrinkPartyPack extends Composite
{
public ColdDrinkPartyPack(List items)
{
super.addAll(items);
}
public double getPrice()
{
return super.getPrice() - super.getPrice()*.25; // get 25% discount on family pack
}
}
Composite.Java
import java.util.*;
public abstract class Composite implements Item
{
List<Item> items = new ArrayList<Item>();
public void add(Item itm)
{
items.add(itm);
}
public void remove(Item itm)
{
items.remove(itm);
}
public void addAll(List lst)
Page | 41
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
items.addAll(lst);
}
public double getPrice()
{
double sum=0;
for (Item i: items)
{
sum += i.getPrice();
}
return sum;
}
}
Item.Java
public interface Item
{
public double getPrice();
}
Output:
Page | 42
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Program 7. Master-Slave Design Pattern
Pattern Instance:
Class Diagram:
Page | 43
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
Java Code:
Master.java:
public class Master
{
private Resource resource;
private int sk=2;
private Resource res=new Resource();
private Slave[] slave=new Slave[sk];
public Resource getResource()
{
return resource;
}
public void setResource(Resource theResource)
{
resource = theResource;
}
public void slave()
{
}
public void run()
{
for(int i=0;i<sk;i++)
slave[i]=new Slave(res);
for(int i=0;i<sk;i++)
slave[i].start();
for(int i=0;i<sk;i++)
{
try
{
slave[i].join();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
Page | 44
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
System.out.println(slave[i].getName()+"--has died");
}
}
System.out.println("Master Exiting now");
}
public void start()
{
}
}
Slave.java
public class Slave extends Thread
{
private Resource resource;
private Resource sharedResource;
private Boolean done=false;
public void halt()
{
done=true;
}
public Slave(Resource res)
{
sharedResource=res;
}
protected boolean task()
{
int status=sharedResource.innerStatus();
return(status>7);
}
public Resource getResource()
{
return resource;
}
public void setResource(Resource theResource)
{
resource = theResource;
}
public void run()
{
Page | 45
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
while(done!=true)
{
done=task();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
}
}
}
Resource.java
public class Resource
{
private TestMaster testmaster;
private int status=0;
public synchronized int innerStatus()
{
int local=status;
System.out.println("Ststus="+local);
local++;
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
status=local;
System.out.println("New Status="+local);
return status;
}
public TestMaster getTestmaster()
Page | 46
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
return testmaster;
}
public void setTestmaster(TestMaster theTestmaster)
{
testmaster = theTestmaster;
}
private Master master;
public Master getMaster()
{
return master;
}
public void setMaster(Master theMaster)
{
master = theMaster;
}
private Slave slave;
public Slave getSlave()
{
return slave;
}
public void setSlave(Slave theSlave)
{
slave = theSlave;
}
public void status()
{
}
}
TestMaster.java
public class TestMaster
{
private Resource resource;
public Resource getResource()
{
return resource;
}
public void setResource(Resource theResource)
Page | 47
Department of MCA, CMRIT
Software Design Laboratory
Sub. Code 10MCA56
{
resource = theResource;
}
public static void main(String args[])
{
Master ms=new Master();
ms.run();
}
}
Output:
Page | 48
Department of MCA, CMRIT