You are on page 1of 98

Sub: Software Design Laboratory

Sub Code:13MCA56

INDEX
SL.
NO.
1.
2.
3.
4.
5.
6
7.
8.
9.
10.
11.

STAFF
DATE

USN: 2VX13MCA06

NAME OF EXPERIMENT
Expert
Controller
Publisher-Subscriber
Command
Forward-Receive
Client-Dispatcher
Proxy
Facade
Polymorphism
Whole-Part
Master-Slave

PAGE NO

SIGNATURE

Page 1

Sub: Software Design Laboratory


Sub Code:13MCA56
1) Expert
Problem:
What is the most basic principle by which responsibilities are assigned in object-oriented design?
Solution:
Assign a responsibility to the class that has the information necessary to fulfill the responsibility.
A Design Model may define hundreds or thousands of software classes, and an application may
require hundreds or thousands of responsibilities to be fulfilled. During object design, when the
interactions between objects are defined, we make choices about the assignment of responsibilities to
software classes. If we've chosen well, systems tend to be easier to understand, maintain, and extend,
and our choices afford more opportunity to reuse components in future applications.
Example:
A Point of Sale(POS) system is a computerized application used in a retail store. It is used to record
sales and handle payments;
A commercial POS system will sell to different clients with disparate needs in terms of business rule
processing. The POS will calculate the total sales at any given point of time Who should be
responsible for knowing the grand total of a sale?
Structure:
By Information Expert, we should look for that class of objects that has the information needed to
determine the total.
Participants:
Information Expert: This is the class, which has the information to fulfill the responsibility. We
Assign the responsibility to this class to accomplish the behavior.
Use Case Diagram:
Actor:
The user is the ACTOR who is interacting with the POS(Point of Sale) to get the GrandTotal.

USN: 2VX13MCA06

Page 2

Sub: Software Design Laboratory


Sub Code:13MCA56

Get Total Price

Activity Diagram:

USN: 2VX13MCA06

Page 3

Sub: Software Design Laboratory


Sub Code:13MCA56

Class Diagram:

Sequence Diagram:

USN: 2VX13MCA06

Page 4

Sub: Software Design Laboratory


Sub Code:13MCA56

Communication Diagram:

USN: 2VX13MCA06

Page 5

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
ProductDescription.java
public class ProductDescription
{
public SaleCounter SaleCounter;
private float price=43.89f;
public float getPrice()
{
return price;
}
}

Sale.java
public class Sale
{
public SaleCounter SaleCounter;
private float total;
public float getTotal()
{
ProductDescription pd=new ProductDescription();
SalesLineItem sli=new SalesLineItem();
total =( pd.getPrice() * sli.getSubTotal());
return total;
}
USN: 2VX13MCA06

Page 6

Sub: Software Design Laboratory


Sub Code:13MCA56
}

SaleCounter.java
public class SaleCounter
{
public Sale Sale;
public SalesLineItem SalesLineItem;
public ProductDescription ProductDiscription;
public static void main(String []args)
{
float total;
Sale s=new Sale();
total=s.getTotal();
System.out.println(" Total sale is :" + total);
}
}
SalesLineItem.java
public class SalesLineItem
{
public SaleCounter SaleCounter;
private int quantity=100;
public int getSubTotal()
{
return quantity;
}
}
USN: 2VX13MCA06

Page 7

Sub: Software Design Laboratory


Sub Code:13MCA56

Output:
The Total Sale is 4389.00

2) Controller
Problem:
The presentation-tier request handling mechanism must control and coordinate processing of each
user across multiple requests. Such control mechanisms may be managed in either a centralized or
centralized manner.
Solution:
Use a controller as the initial point of contact for handling a request. The controller manages the
handling of the request, including invoking security services such as authentication and
authorization, delegating business processing, managing the choice of an appropriate view,
handling errors, and managing the selection of content creation strategies.
Participants:
Controller:
The controller is the initial contact point for handling all requests in the system. The controller
may delegate to a helper to complete authentication and authorization of a user or to initiate
contact retrieval.
Dispatcher:
A dispatcher is responsible for view management and navigation, managing the choice of the
next view to present to the user, and providing the mechanism for vectoring control to this
resource.
Helper:
A helper is responsible for helping a view or controller complete its processing. Helpers can
service requests for data from the view by simply providing access to the raw data or by
formatting the data as Web content.
View:
A view represents and displays information to the client. The view retrieves information from a
model. Helpers support views by encapsulating and adapting the underlying data model for use
in the display
USN: 2VX13MCA06

Page 8

Sub: Software Design Laboratory


Sub Code:13MCA56
Example: A Point Of Sale(POS) system
Its is a computerized application used (in part) to record sales and handle payments; it is typically
used in a retail store. It interfaces to various service applications, such as a third-party tax calculator
and inventory control.
Creating a commercial POS system that will sell to different clients with disparate needs in terms of
business rule processing. Each client will desire a unique set of logic to execute at certain predictable
points in scenarios of using the system, such as when a new sale is initiated or when a new line item
is added. Therefore, we will need a mechanism to provide this flexibility and customization. The
POS will be calculating the total sales at any given point of time.
The Controller Pattern suggests that events coming from UI layer should not be directly accessing
the expert classes like Sale which calculates total sale. There should be a Controller class to control
these events.
In this example, SaleController class that will be receiving the events from UI and forward it to the
Sale class.
View class decides how the output will be displayed. In this example Console is used for taking
input, and displaying the output.
UseCase Diagram:
Actor:
The user is the ACTOR who is interacting with the POS(Point of Sale) to get the GrandTotal.
UseCase:
What information do we need to determine the grand total? We need to know about all the
SalesLineItem instances of a sale and the sum of their subtotals. A Sale instance contains these.
The Use case diagram:

USN: 2VX13MCA06

Page 9

Sub: Software Design Laboratory


Sub Code:13MCA56

Activity Diagram:

Class Diagram:

USN: 2VX13MCA06

Page 10

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

Communication Diagram:

USN: 2VX13MCA06

Page 11

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
Client.java
import java.util.Scanner;
public class Client
{
public SaleController SaleController;
public static SaleController getController()
{
SaleController tc = new SaleController();
Sale s=new Sale();
view v=new view();
tc.setSale(s);
tc.setView(v);
return tc;
USN: 2VX13MCA06

Page 12

Sub: Software Design Laboratory


Sub Code:13MCA56
}
public static void main(String[] args)
{
SaleController tc = getController();
Scanner scr=new Scanner(System.in);
System.out.println("Enter the Qunatity: ");
int quantity= scr.nextInt();
System.out.println("Enter the Price: ");
float price=scr.nextFloat();
tc.execute(quantity, price);
}
}

Sale.java
public class Sale
{
public SaleController SaleController;
public float getTotal(int quantity, float price)
{
return quantity * price;
}
}

SaleController.java
public class SaleController
{
USN: 2VX13MCA06

Page 13

Sub: Software Design Laboratory


Sub Code:13MCA56
public Client Client;
public Sale sale;
public view view;
public void execute(int quantity,float price)
{
float result = sale.getTotal(quantity, price);
view.display(result);
}
public void setSale(Sale sale)
{
this.sale = sale;
}

public void setView(view view)


{
this.view = view;
}
}

view.java
public class view
{
public SaleController SaleController;
public void display(float total)
{
System.out.println("The Total Sale is: " + total);
USN: 2VX13MCA06

Page 14

Sub: Software Design Laboratory


Sub Code:13MCA56
}
}

Output:
Enter the Quantity
20
Enter the price
5.0
The Total Sale is: 100.0

USN: 2VX13MCA06

Page 15

Sub: Software Design Laboratory


Sub Code:13MCA56
3) Publisher-Subscriber/ Observer Pattern
"The Publisher-Subscriber design pattern helps to keep the state of cooperating components
synchronized. It enables one-way propagation of changes: one publisher notifies any number of
subscribers about changes to its state."
Problem
Need to synchronize the state of cooperating components.
Solution
-

One dedicated component takes the role of the publisher.


All components dependent on changes in the publisher are its subscribers.
The publisher maintains a registry of currently-subscribed components.
Component can subscriber (uses the subscribe interface of publisher) or unsubscribe.

Whenever the publisher changes state, it sends a notification to all its subscribers.
- The subscribers in turn retrieve the changed data at their discretion
Participants
Concrete Subject:
Acts as a Publisher. It is responsible for notifying and updating the changes taking place in
data.
Concrete Observer:
- Acts as subscriber. The changes made to the Concrete Subject(Publisher) will be reflected to
it.
Example: Weather Information system
The weather Station will be broadcasting the current weather conditions like temperature,
humidity and pressure. The application receives the weather conditions and displays them in
different forms.(i.e. displaying the current weather conditions, displaying weather forecast). All
displays will be updating the weather conditions in real time.

The Use case diagram:


Actors: Weather reporter who is interacting with the weather information system
USN: 2VX13MCA06

Page 16

Sub: Software Design Laboratory


Sub Code:13MCA56
Usecase: Displaying Current Weather data and Forecasted Weather data.

Activity Diagram:

USN: 2VX13MCA06

Page 17

Sub: Software Design Laboratory


Sub Code:13MCA56

Class Diagram:

USN: 2VX13MCA06

Page 18

Sub: Software Design Laboratory


Sub Code:13MCA56
Sequence Diagram:

Communication Diagram:

USN: 2VX13MCA06

Page 19

Sub: Software Design Laboratory


Sub Code:13MCA56
Code:
CurrentConditionDisplay.java
import java.util.Observable;
import java.util.Observer;
public class CurrentConditionDisplay implements Observer
{
private float temperature;
Observable observable;
public CurrentConditionDisplay(Observable observable)
{
this.observable = observable;
observable.addObserver(this);
}
public void update(Observable obs, Object arg)
{
if(obs instanceof WeatherData)
{
WeatherData weatherData =(WeatherData)obs;
this.temperature = weatherData.getTemprature();
display();
}
}
public void display()
{
System.out.println("Current conditions: " + temperature+ "F degrees ");}
}

USN: 2VX13MCA06

Page 20

Sub: Software Design Laboratory


Sub Code:13MCA56

ForeCastDisplay.java
import java.util.Observable;
import java.util.Observer;
public class ForeCastDisplay implements Observer
{
private float currentPressure = 29.92f, lastPressure;
public ForeCastDisplay(Observable observable)
{
observable.addObserver(this);
}
public void update(Observable observable, Object arg)
{
if(observable instanceof WeatherData)
{
WeatherData weatherData =(WeatherData)observable;
lastPressure = currentPressure;
currentPressure = weatherData.getPressure();
display();
}
}
public void display()
{
System.out.print("Forecast: ");
if(currentPressure > lastPressure)
{
System.out.println("Improving weather on the way!");
USN: 2VX13MCA06

Page 21

Sub: Software Design Laboratory


Sub Code:13MCA56
}
else if(currentPressure == lastPressure)
{
System.out.println("More of the same");
}
else if(currentPressure < lastPressure)
{
System.out.println("Watch out for cooler, rainy weather");
}
}
}
WeatherData.java
import java.util.Observable;
public class WeatherData extends Observable
{
private float temperature, pressure;
public float getTemprature()
{
return temperature;
}
public float getPressure()
{
return pressure;
}
public void setMeasurementsChanged()
{
setChanged();
USN: 2VX13MCA06

Page 22

Sub: Software Design Laboratory


Sub Code:13MCA56
notifyObservers();
}
public void setMeasurements(float temp, float hum, float prs)
{
temperature=temp; pressure=prs;
setMeasurementsChanged();
}
}
WeatherStation.java
public class WeatherStation
{
public static void main(String[] args)
{
WeatherData weatherData = new WeatherData();
CurrentConditionDisplay currentConditions = new CurrentConditionDisplay(weatherData);
ForeCastDisplay forecastDisplay = new ForeCastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}

Output:Forecast: Improving weather on the way!


Current conditions: 80.0F degrees
Forecast: Watch out for cooler, rainy weather
Current conditions: 82.0F degrees
Forecast: More of the same
Current conditions: 78.0F degrees
USN: 2VX13MCA06

Page 23

Sub: Software Design Laboratory


Sub Code:13MCA56

4) Command
"The Command Processor design pattern separates the request for a service from its execution. A
command processor component manages requests as separate objects, schedules their execution, and
provides additional services such as the storing of request objects for later undo."
Problem
- Changes to the user interface should be possible at runtime
- Need to issue requests to objects without knowing anything about the operation being
- requested or the receiver of the request.
Solution
Request is encapsulated into objects. Whenever a user calls a specific function of the application,
the request is turned into a command object. The Command Processor pattern illustrates more
specifically how command objects are managed. A central component of the Command Processor
pattern description takes care of all command objects. The command processor schedules the
execution of commands, may store them for later undo, and may provide other services such as
logging the sequence of commands for testing purposes. Each command object delegates the
execution of its task to supplier components within the functional core of the application.
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
Example: Simple switch
Switch is configured with 2 commands: ON and OFF. Switch can be used with any device, not just a
light but also with other devices like fan, TV, etc.

USN: 2VX13MCA06

Page 24

Sub: Software Design Laboratory


Sub Code:13MCA56

Use Case Diagram:


Actor: User, who is using system.
UseCase: Functionalities provided by the system like, light ON / OFF, fan ON / OFF

Activity Diagram:

USN: 2VX13MCA06

Page 25

Sub: Software Design Laboratory


Sub Code:13MCA56

Class Diagram:

Sequence Diagram:

USN: 2VX13MCA06

Page 26

Sub: Software Design Laboratory


Sub Code:13MCA56

Communication Diagram:

USN: 2VX13MCA06

Page 27

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
Command.java
public interface Command
{
public void execute();
}
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
USN: 2VX13MCA06

Page 28

Sub: Software Design Laboratory


Sub Code:13MCA56
{
Light light;
public LightOnCommand(Light light)
{
this.light = light;
}
public void execute()
{
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.onButtonWasPushed(2);
remoteControl.offButtonWasPushed(2);
}
}

Remotecontrol.java
public class RemoteControl
USN: 2VX13MCA06

Page 29

Sub: Software Design Laboratory


Sub Code:13MCA56
{
Command[] onCommands, offCommands;
public RemoteControl()
{
onCommands = new Command[3];
offCommands = new Command[3];
Command noCommand = new Receiver();
for(int i = 0; i < 3; i++)
{
onCommands[i] = noCommand;offCommands[i] = noCommand;
}
}
public void setCommand(int slot, Command onCommand, Command
offCommand)
{
onCommands[slot] = onCommand;
offCommands[slot] = offCommand;
}
public void onButtonWasPushed(int slot)
{
onCommands[slot].execute();
}
public void offButtonWasPushed(int slot)
{
offCommands[slot].execute();
}
}
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");
}
}
USN: 2VX13MCA06

Page 30

Sub: Software Design Laboratory


Sub Code:13MCA56
Receiver.java
public class Receiver implements Command
{
public void execute()
{
}
}

Output
RemoteControl@814b5bf7
Living Room light is on
Living Room light is off
Kitchen light is on
Kitchen light is off

5) Forwarder-Receiver
"The Forwarder-Receiver design pattern provides transparent interprocess communication for
software systems with a peer-to-peer interaction model. It introduces forwarders and receivers to
decouple peers from the underlying communication mechanisms."\
Participants
Forwarder:
-

Its a components 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.


It contains a mapping from names to physical addresses.
When a forwarder sends a message to a remote peer, it determines the physical location of

the recipient by using its name-to-address mapping.


In the transmitted message the forwarder specifies the name of its own peer, so that the
remote peer is able to send a response to the message originator.

Receiver
-

Its a component 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.

USN: 2VX13MCA06

Page 31

Sub: Software Design Laboratory


Sub Code:13MCA56
Example: Applications for the management of computer networks
Use Case Diagram:
Actor:
Peer is the actor; he is interacting with the system for sending and receiving the message.
Use Case:
Send message and receive message are the two functionalities so they are the use cases here.

Activity Diagram:

USN: 2VX13MCA06

Page 32

Sub: Software Design Laboratory


Sub Code:13MCA56

USN: 2VX13MCA06

Page 33

Sub: Software Design Laboratory


Sub Code:13MCA56
Class Diagram:

Sequence Diagram:

USN: 2VX13MCA06

Page 34

Sub: Software Design Laboratory


Sub Code:13MCA56

Communication Diagram:

USN: 2VX13MCA06

Page 35

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
USN: 2VX13MCA06

Page 36

Sub: Software Design Laboratory


Sub Code:13MCA56
Entry.java
class Entry
{
private String destinationId; // target machine
private int portNr; // socket port
public Entry(String theDest, int theport)
{
destinationId = theDest;
portNr = theport;
}
public String dest()
{
return destinationId;
}
public int port()
{
return portNr;
}
}

Forwarder.java
import java.io.*;
import java.net.Socket;
public class Forwarder
{
public Server Forwarder;
private Socket s;
USN: 2VX13MCA06

Page 37

Sub: Software Design Laboratory


Sub Code:13MCA56
private OutputStream oStr;
private String myName;
private Registry reg;
public Forwarder(String theName,Registry reg)
{
myName = theName;
this.reg=reg;
}
private byte[] marshal(Message theMsg)
{
return theMsg.data.getBytes();
}
private void deliver(String theDest, byte[] data)
{
try
{
Entry entry = reg.get(theDest);
s = new Socket(entry.dest() ,entry.port());
oStr = s.getOutputStream();
oStr.write(data);
oStr.flush();
oStr.close();
s.close();
}
catch(IOException e)
{
System.out.println("Forerror"+e);
USN: 2VX13MCA06

Page 38

Sub: Software Design Laboratory


Sub Code:13MCA56
}
}
public void sendMsg(String theDest , Message theMsg)
{
deliver(theDest, marshal(theMsg));
}
}

Message.java
class Message
{
public String sender;
public String data;
public Message(String thesender, String rawData)
{
sender = thesender;
data = rawData;
}
}

Receiver.java
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Receiver
{
USN: 2VX13MCA06

Page 39

Sub: Software Design Laboratory


Sub Code:13MCA56
private ServerSocket srvS;
private Registry reg;
private Socket s;
private InputStream iStr;
private String myName;
public Receiver(String theName,Registry reg)
{
myName = theName;
this.reg=reg;
try
{
Entry entry = reg.get(myName);
srvS = new ServerSocket(entry.port());
System.out.println("Server started");
}
catch(Exception e)
{
e.printStackTrace();
}
//System.out.println(reg.get(theName).port());
}
private Message unmarshal(byte [] anarray)
{
return new Message(myName,new String(anarray));
}

private byte[] receive()


USN: 2VX13MCA06

Page 40

Sub: Software Design Laboratory


Sub Code:13MCA56
{
int val;
byte buffer [] = null;
try
{
s = srvS.accept();
iStr = s.getInputStream();
val = iStr. read();
buffer = new byte [val] ;
iStr.read(buffer);
iStr.close();
s.close();
srvS.close();
}
catch(IOException e)
{
System.out.println("Error"+ e);
}
return buffer;
}
public Message receiveMsg()
{
return unmarshal(receive());
}
}

Registry.java
USN: 2VX13MCA06

Page 41

Sub: Software Design Laboratory


Sub Code:13MCA56
import java.util.*;
class Registry
{
private Hashtable hTable = new Hashtable();
public void put(String theKey, Entry theEntry)
{
hTable.put(theKey,theEntry);
}
public Entry get(String aKey)
{
return(Entry) hTable.get(aKey);
}
}
Server.java
class Server
{
Receiver r;
Forwarder f;
static Registry reg=new Registry();
public void execute()
{
Message result = null;
r = new Receiver( "Server",reg);
f = new Forwarder("Server" ,reg);
Message msg = new Message("Server"," WE ALL ARE STILL ALIVE");
f.sendMsg("Server", msg);
result = r.receiveMsg();
USN: 2VX13MCA06

Page 42

Sub: Software Design Laboratory


Sub Code:13MCA56
System.out.println( result.data.trim());
}
public static void main(String args[])
{
Entry entry = new Entry("127.0.0.1", 2900);
reg.put("Client", entry);
entry = new Entry("127.0.0.1",2900);
reg.put("Server", entry);
new Server().execute();
}
}

Output:Server started
WE ALL ARE STILL ALIVE

USN: 2VX13MCA06

Page 43

Sub: Software Design Laboratory


Sub Code:13MCA56
6) Client-Dispatcher
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. However, the core functionality of the components should be separate from the details of
communication mechanisms. Clients should not need to know where servers are located. This allows
you to change the location of servers dynamically, and provides resilience to network or server
failures.
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.
Participants
The Client:
-

Performs domain-specific tasks.


The client accesses operations offered by server.
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:
USN: 2VX13MCA06

Page 44

Sub: Software Design Laboratory


Sub Code:13MCA56
-

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.


It 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.


To provide its name service, the dispatcher implements functions for registering and locating
servers.

Example: A software system for the retrieval of new scientific information.


The information providers are both on our local network and distributed over the world. To access an
individual information provider, it is necessary to specify its location and the service to be executed.
When an information provider receives a request from a client application, it runs the appropriate
service and returns the requested information to the client.
Use Case Diagram:

USN: 2VX13MCA06

Page 45

Sub: Software Design Laboratory


Sub Code:13MCA56

Activity Diagram:

Class Diagram:

USN: 2VX13MCA06

Page 46

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 47

Sub: Software Design Laboratory


Sub Code:13MCA56

USN: 2VX13MCA06

Page 48

Sub: Software Design Laboratory


Sub Code:13MCA56
Communication Diagram:

USN: 2VX13MCA06

Page 49

Sub: Software Design Laboratory


Sub Code:13MCA56
Code:
CDS.java
public class CDS
{
public static Dispatcher disp = new Dispatcher();
public static void main(String[] args)
{
Service sl = new PrintService("printSvc1","srvl");
Service s2 = new PrintService("printSvc2","srv2");
Client client = new Client();
client.doTask();
}
}

Client.java
public class Client
{
private Dispatcher dispatcher;
private PrintService printservice;
public void doTask()
{
Service s;
try
{
s = CDS.disp. locateServer("printSvc1"); s.runService();
}
USN: 2VX13MCA06

Page 50

Sub: Software Design Laboratory


Sub Code:13MCA56
catch(NotFound n) { System.out.println("Not available");
}
try
{
s = CDS.disp.locateServer("printSvc2"); s.runService();
}
catch(NotFound n) { System.out.println("Not available");
}
try
{
s = CDS.disp.locateServer("drawSvc"); s.runService();
}
catch(NotFound n) { System.out.println("Not available");
}
}
}

Dispatcher.java
import java.util.*;
class NotFound extends Exception {}
public class Dispatcher
{
private Client client;
private PrintService printservice;
Hashtable registry = new Hashtable();
Random rnd = new Random(123456); // for random access
public void registerService(String svc, Service obj)
USN: 2VX13MCA06

Page 51

Sub: Software Design Laboratory


Sub Code:13MCA56
{
Vector v = (Vector) registry.get(svc);
if(v == null)
{
v = new Vector();
registry.put(svc, v);
}
v.addElement(obj);
}
public Service locateServer(String svc)throws NotFound
{
Vector v =(Vector) registry.get(svc);
if(v == null) throw new NotFound();
if(v.size() == 0) throw new NotFound();
return (Service)v.elementAt(rnd.nextInt() % v.size());
}
}
PrintService.java
public class PrintService extends Service
{
public PrintService(String svc, String srv)
{
super(svc, srv);
}
public void runService()
{
System.out.println("Service " + nameofservice + " by " +nameofserver);
USN: 2VX13MCA06

Page 52

Sub: Software Design Laboratory


Sub Code:13MCA56
}
}
Service.java
public abstract class Service
{
String nameofservice, nameofserver; // service name, server name
public Service(String svc, String srv)
{
nameofservice = svc; nameofserver = srv;
CDS.disp.registerService(nameofservice,this);
}
abstract public void runService(); // service provided
}

Output:Service printSvc1 by srvl


Service printSvc2 by srv2
Not available

USN: 2VX13MCA06

Page 53

Sub: Software Design Laboratory


Sub Code:13MCA56
7) Proxy
The Proxy design pattern makes the clients of a component communicate with a representative rather
than to the component Itself. Introducing such a placeholder can serve many purposes, including
enhanced efficiency, easier access and protection from unauthorized access.
Problem:
It is often inappropriate to access a component directly. We do not want to hard-code its physical
location into clients, and direct and unrestricted access to the component may be inefficient or even
insecure. Additional control mechanisms are needed.
Solution:
Let the client communicate with a representative rather than the component itself. This
representative-called a proxy-offers the interface of the component but performs additional pre- and
postprocessing such as access-control checking or making read-only copies of the original.
Participants:
Proxy: ProxyEmailService
Subject: EmailService
Real Subject: RealEmailService
Example:
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.
Use Case Diagram:

USN: 2VX13MCA06

Page 54

Sub: Software Design Laboratory


Sub Code:13MCA56

Activity Diagram:

USN: 2VX13MCA06

Page 55

Sub: Software Design Laboratory


Sub Code:13MCA56

Class Diagram:

USN: 2VX13MCA06

Page 56

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 57

Sub: Software Design Laboratory


Sub Code:13MCA56

Communication Diagram:
USN: 2VX13MCA06

Page 58

Sub: Software Design Laboratory


Sub Code:13MCA56

USN: 2VX13MCA06

Page 59

Sub: Software Design Laboratory


Sub Code:13MCA56
Code:
Application.java
public class Application
{
public EMailService locateEMailService()
{
return new ProxyEMailService();
}
}
ApplicationClient.java
public class ApplicationClient
{
public static void main(String[] args)
{
Application application = new Application();
EMailService emailService = application.locateEMailService();
emailService.sendMail("abcd@gmail.com", "Hello", "A test mail");
emailService.receiveMail("abcd@gmail.com");
}
}
EMailService.java
public interface EMailService
{
public void sendMail(String receiver, String subject, String text);
public void receiveMail(String receiver); }
USN: 2VX13MCA06

Page 60

Sub: Software Design Laboratory


Sub Code:13MCA56
ProxyEMailService.java
public class ProxyEMailService implements EMailService
{
private RealEMailService emailService;
public void receiveMail(String receiver)
{
if(emailService == null)
{
emailService = new RealEMailService();
}
emailService.receiveMail(receiver);
}
public void sendMail(String receiver, String subject, String text)
{
if(emailService == null)
{
emailService = new RealEMailService();
}
emailService.sendMail(receiver, subject, text);
}
}

USN: 2VX13MCA06

Page 61

Sub: Software Design Laboratory


Sub Code:13MCA56

RealEMailService.java
public class RealEMailService implements EMailService
{
public void sendMail(String receiver, String subject, String text)
{
System.out.println("Sending mail to '" + receiver + "'" + " with subject '" + subject + "'" +
" and message '" + text + "'");
}
public void receiveMail(String receiver)
{
System.out.println("Receiving mail from '" + receiver + "'");
}
}

Output:Sending mail to 'abcd@gmail.com' with subject 'Hello' and message 'A test mail'
Receiving mail from 'abcd@gmail.com'

USN: 2VX13MCA06

Page 62

Sub: Software Design Laboratory


Sub Code:13MCA56
8) Faade
A segment of the client community needs a simplified interface to the overall functionality of a
complex subsystem. Faade defines a higher-level interface that makes the subsystem easier to use.
Problem:
In almost every software system objects that are composed of other objects exist.
Solution:
-

Structuring a system into subsystems helps reduce complexity


Subsystems are groups of classes, or groups of classes and other subsystems
The interface exposed by the classes in a subsystem or set of subsystems can become quite

complex
One way to reduce this complexity is to introduce a facade object that provides a single,
simplified interface to the more general facilities of a subsystem

Participants:
Facade: HomeTheatreFacade
Subsystems: Amplifier, DvdPlayer, Projector
Example: Home Theater System
The home theater system will consist of different components like Projector, to project the movie on
screen, DVD Player to play the movie, Amplifier to control the sound effects.
For watching a movie the user starts switching on each component one by one and enjoys the movie.
After watching the movie he/she will have to switch off each device. But now the user is fed up of
this process and dont want to start switching on each device by him. He wants to control all the
devices
using single remote so that when he wants to watch a movie he can use this remote to start watching
movie and in the end he can close all the devices by one command using same remote.

USN: 2VX13MCA06

Page 63

Sub: Software Design Laboratory


Sub Code:13MCA56
Use Case Diagram:

Activity Diagram:

USN: 2VX13MCA06

Page 64

Sub: Software Design Laboratory


Sub Code:13MCA56

Class Diagram:

USN: 2VX13MCA06

Page 65

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 66

Sub: Software Design Laboratory


Sub Code:13MCA56

USN: 2VX13MCA06

Page 67

Sub: Software Design Laboratory


Sub Code:13MCA56
Communication Diagram:

USN: 2VX13MCA06

Page 68

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
Amplifier.java
public class Amplifier
{
String description;
DvdPlayer dvd;
public Amplifier(String description)
{
this.description = description;
}
public void on()
{
System.out.println(description + " on");
}
public void off()
USN: 2VX13MCA06

Page 69

Sub: Software Design Laboratory


Sub Code:13MCA56
{
System.out.println(description + " off");
}
public String toString()
{
return description;
}
}

DvdPlayer.java
public class DvdPlayer
{
String description, movie;
Amplifier amplifier;
public DvdPlayer(String description, Amplifier amplifier)
{
this.description = description;
this.amplifier = amplifier;
}
public void on()
{
System.out.println(description + " on");
}
public void off()
USN: 2VX13MCA06

Page 70

Sub: Software Design Laboratory


Sub Code:13MCA56
{
System.out.println(description + " off");
}
public void play(String movie)
{
this.movie = movie;
System.out.println(description + " playing \"" + movie + "\"");
}
public void stop()
{
System.out.println(description + " stopped \"" + movie + "\"");
}
public String toString()
{
return description;
}
}
HomeTheaterFacade.java
public class HomeTheaterFacade
{
Amplifier amp;
DvdPlayer dvd;
Projector projector;
HomeTheaterFacade(Amplifier amp, DvdPlayer dvd, Projector prj)
{
this.amp = amp;
this.dvd = dvd;
USN: 2VX13MCA06

Page 71

Sub: Software Design Laboratory


Sub Code:13MCA56
this.projector = prj;
}
public void watchMovie(String movie)
{
System.out.println("Get ready to watch a movie...");
projector.on();
amp.on();
dvd.on();
dvd.play(movie);
}

public void endMovie()


{
System.out.println("Shutting movie theater down...");
projector.off();
amp.off();
dvd.stop();
dvd.off();
}
}

Projector.java
public class Projector
{
String description;
DvdPlayer dvdPlayer;
USN: 2VX13MCA06

Page 72

Sub: Software Design Laboratory


Sub Code:13MCA56
public Projector(String description, DvdPlayer dvdPlayer)
{
this.description = description;
this.dvdPlayer = dvdPlayer;
}
public void on()
{
System.out.println(description + " on");
}
public void off()
{
System.out.println(description + " off");
}
public void tvMode()
{
System.out.println(description + " in tv mode");
}
public String toString()
{
return description;
}
}

User.java
public class User
{
public static void main(String[] args)
USN: 2VX13MCA06

Page 73

Sub: Software Design Laboratory


Sub Code:13MCA56
{
Amplifier amp = new Amplifier("Top-O-Line Amplifier");
DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp);
Projector projector = new Projector("Top-O-Line Projector", dvd);
HomeTheaterFacade homeTheater =
new HomeTheaterFacade(amp, dvd, projector);
homeTheater.watchMovie("Write your own movie name !!");
homeTheater.endMovie();
}
}

Output:Get ready to watch a movie...


Top-O-Line Projector on
Top-O-Line Amplifier on
Top-O-Line DVD Player on
Top-O-Line DVD Player playing "Write your own movie name !!"
Shutting movie theater down...
Top-O-Line Projector off
Top-O-Line Amplifier off
Top-O-Line DVD Player stopped "Write your own movie name !!"
Top-O-Line DVD Player off

USN: 2VX13MCA06

Page 74

Sub: Software Design Laboratory


Sub Code:13MCA56
9) Polymorphism
Problem:
How to handle alternatives based on type?
How to create pluggable software components?
Solution:
When related alternatives or behaviors vary by type(class), assign responsibility for the behavior
using polymorphic operations to the types for which the behavior varies.
Participants:
TheInterface:
This interface will provide the behavior which varies according to the class type. All classes
implementing this interface will write the method accordingly.
Implementer:
The classes will implement the operations from the interface as per the polymorphic nature.
Example: Application to draw different shapes
The user will use this application to draw shapes like Circle, Rectangle, triangle. At a later stage we
can have some more shapes be added to the application.
Use case diagram

USN: 2VX13MCA06

Page 75

Sub: Software Design Laboratory


Sub Code:13MCA56

Activity Diagram:
draw Circle

draw Triangle

draw Rectangle

Class Diagram:

USN: 2VX13MCA06

Page 76

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 77

Sub: Software Design Laboratory


Sub Code:13MCA56

USN: 2VX13MCA06

Page 78

Sub: Software Design Laboratory


Sub Code:13MCA56

Communication Diagram:

USN: 2VX13MCA06

Page 79

Sub: Software Design Laboratory


Sub Code:13MCA56

Code:
Shape.java
public interface Shape
{
public void draw();
}

Circle.java
public class Circle implements Shape
{
public void draw()
{
System.out.println("This is a Circle");
}
}
Rectangle.java
public class Rectangle implements Shape
{
public void draw()
{
System.out.println("This is a Rectangle");
}
}

USN: 2VX13MCA06

Page 80

Sub: Software Design Laboratory


Sub Code:13MCA56

Triangle.java
public class Triangle implements Shape
{
public void draw()
{
System.out.println("This is a Triangle");
}
}
DrawShape.java
public class DrawShape
{
private static Shape shape;
public static void main(String a[])
{
System.out.println("Invoking Circles draw method..");
shape = new Circle();
shape.draw();
System.out.println("Invoking Rectangles draw method..");
shape = new Rectangle();
shape.draw();
System.out.println("Invoking Triangles draw method..");
shape = new Triangle();
shape.draw();
}
}
USN: 2VX13MCA06

Page 81

Sub: Software Design Laboratory


Sub Code:13MCA56

Output:Invoking Circles draw method..


This is a Circle
Invoking Rectangles draw method..
This is a Rectangle
Invoking Triangles draw method..
This is a Triangle

USN: 2VX13MCA06

Page 82

Sub: Software Design Laboratory


Sub Code:13MCA56
10) Whole-Part
Helps with the aggregation of components (parts) that together form a semantic unit (whole). Direct
access to the Parts is not possible. Whole-Part lets clients treat individual objects and compositions
of object uniformly
Problem:

Software system objects that are composed of other objects exist.

A complex object should either be decomposed into smaller objects, or composed of existing
objects, to support reusability, changeability and the recombination of the constituent objects in
other types of aggregate.

Clients should see the aggregate object as an atomic object that does not allow any direct access
to its constituent parts.

Solution:

Introduce a component that encapsulates smaller objects, and prevents clients from accessing
these constituent parts directly.

Define an interface for the aggregate that is the only means of access to the functionality of the
encapsulated objects, allowing the aggregate to appear as a semantic unit.

Usecase Diagram

USN: 2VX13MCA06

Page 83

Sub: Software Design Laboratory


Sub Code:13MCA56

Activity Diagram:

Class Diagram:

USN: 2VX13MCA06

Page 84

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 85

Sub: Software Design Laboratory


Sub Code:13MCA56
Communication Diagram:

USN: 2VX13MCA06

Page 86

Sub: Software Design Laboratory


Sub Code:13MCA56
Code:
Application.Java
import java.util.*;
//collection (several colddrinks) as a whole (pack)
public class Application
{
public Application()
{
}
@SuppressWarnings("unchecked")
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));
ColdDrinkFamilyPack familyPack = new ColdDrinkFamilyPack(items);
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(partyPack.getPrice());
}
}

USN: 2VX13MCA06

Page 87

Sub: Software Design Laboratory


Sub Code:13MCA56

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 void setItemName(String itemName)
{
this.itemName = itemName;
}*/
public String getItemName()
{
return itemName;
}
/*public void setIemDesc(String iemDesc)
{
this.iemDesc = iemDesc;
}*/
public String getIemDesc()
{
return iemDesc;
}
}
USN: 2VX13MCA06

Page 88

Sub: Software Design Laboratory


Sub Code:13MCA56

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
{
/**
* @associates <{demp.composite.Item}>
*/
List<Item> items = new ArrayList<Item>();
public void add(Item itm)
{
USN: 2VX13MCA06

Page 89

Sub: Software Design Laboratory


Sub Code:13MCA56
items.add(itm);
}
public void remove(Item itm)
{
items.remove(itm);
}
public void addAll(List lst)
{
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
38.25
61.5

USN: 2VX13MCA06

Page 90

Sub: Software Design Laboratory


Sub Code:13MCA56
11) Master-Slave
The Master-Slave pattern is often used for multi-threaded applications in which many instances of
the same problem must be solved. The master creates and launches slaves to solve these instances in
"parallel". When all of the slaves have finished, the master harvests the results.
Example:
A multithreaded implementation of any parallelized divide-and-conquer algorithm
Solution:
Master slave design pattern uses divide and conquer concept , in this pattern instance one master
and n number slaves, where master divide s the responsibilities to slaves, here both master and
slaves uses the same resources, in the program we are using the multithreading concept
Multithreading:
a. create a thread by extending 'Thread' class
b. then run() method , which acts as the thread's entry point
c. start() method invokes the execution of the thread, by calling run()
UseCase Diagram

USN: 2VX13MCA06

Page 91

Sub: Software Design Laboratory


Sub Code:13MCA56
Activity Diagram

Class Diagram:

USN: 2VX13MCA06

Page 92

Sub: Software Design Laboratory


Sub Code:13MCA56

Sequence Diagram:

USN: 2VX13MCA06

Page 93

Sub: Software Design Laboratory


Sub Code:13MCA56

Comm
unication Diagram:

USN: 2VX13MCA06

Page 94

Sub: Software Design Laboratory


Sub Code:13MCA56
Code:
TestMaster.java
public class TestMaster
{
public static void main(String[] args)
{
Master master = new Master();
master.run();
}
}
Master. Java:
public class Master
{
private int slaveCount = 2;
private Resource res = new Resource();
private Slave[] slaves = new Slave[slaveCount];
public void run() {
// create slaves:
for(int i = 0; i < slaveCount; i++)
{
slaves[i] = new Slave(res);
}
// start slaves:
for(int i = 0; i < slaveCount; i++)
{
slaves[i].start();
}
// wait for slaves to die:
for(int i = 0; i < slaveCount; i++)
{
try
{
//is used to wait for a thread to finish and terminate
slaves[i].join();
}
catch(InterruptedException ie)
{
System.err.println(ie.getMessage());
}
finally
{
USN: 2VX13MCA06

Page 95

Sub: Software Design Laboratory


Sub Code:13MCA56
System.out.println(slaves[i].getName() + " has died");
}
}
System.out.println("The master will now die ... ");
}
}
Slave.Java:
class Slave extends Thread
{
private Resource sharedResource;
private boolean done = false;
//constructor
public Slave(Resource rcs)
{
sharedResource = rcs;
}
public void halt()
{
done = true;
}
protected boolean task()
{
// access sharedResource here
int status = sharedResource.incStatus();
return (status >= 20);
}
public void run()
{
while (done != true)
{
done = task();
// be cooperative:
try {
Thread.sleep(500);
} // sleep for 1 sec.
catch (Exception e)
{
}
}
}
}

USN: 2VX13MCA06

Page 96

Sub: Software Design Laboratory


Sub Code:13MCA56

Resourcs.Java:
public class Resource
{
private int status = 0;
public synchronized int incStatus()
{
int local = status;
System.out.println("status = " + local);
local++;
try {
Thread.sleep(50);
} catch(Exception e) {
}
status = local;
System.out.println("now status = " + local);
return status;
}
}
OUTPUT
status = 0
now status = 1
status = 1
now status = 2
status = 2
now status = 3
status = 3
now status = 4
status = 4
now status = 5
status = 5
now status = 6
status = 6
now status = 7
status = 7
now status = 8
status = 8
now status = 9
status = 9
now status = 10
USN: 2VX13MCA06

Page 97

Sub: Software Design Laboratory


Sub Code:13MCA56
status = 10
now status = 11
status = 11
now status = 12
status = 12
now status = 13
status = 13
now status = 14
status = 14
now status = 15
status = 15
now status = 16
status = 16
now status = 17
status = 17
now status = 18
status = 18
now status = 19
status = 19
now status = 20
status = 20
now status = 21
Thread-5 has died
Thread-6 has died
The master will now die ...

USN: 2VX13MCA06

Page 98

You might also like