Sunteți pe pagina 1din 43

10MCA56 : Software Design Laboratory

Page No.:

1. Publisher-Subscriber(Observer)
Intent:
The Publisher/Subscriber model is where the Subscriber is the service to which all
clients subscribe and the Publisher is the service which sends messages to all clients who
have subscribed to the Subscriber service. That is, suppose we have 10 clients and all 10
clients would subscribe to the Subscriber service to receive notifications (client programs are
individual programs), and then whenever the required event occurs, the Publisher notifies all
those clients registered.
Description:
Publisher/Subscriber is a messaging pattern where senders of messages, called
publishers, do not program the messages to be sent directly to specific receivers, called
subscribers. Instead, published messages are characterized into classes, without knowledge of
what, if any, subscribers there may be. Similarly, subscribers express interest in one or more
classes, and only receive messages that are of interest, without knowledge of what, if any,
publishers there are.
Example:
The weather forecasting system, which gives the details about the weather conditions.
It provides the details about the temperature conditions. The conditions includes the pressure,
humidity level and temperature.
Participants:
ConcreteSubject: WeatherData
ConcreteObserver:currentCondidtionDisplay, ForecastDisplay
Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:

Class Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

WeatherData.java
import java.util.Observable;
public class WeatherData extends Observable {
private float temp;
public float getTemp() {
return temp;
}
private float pres;
public float getPres() {
return pres;
}
private float hum;
public float getHum() {
return hum;
}
public void mChanged() {
setChanged();
notifyObservers();
}
public void setMeasurements(float theTemp, float theHum, float thePres)
{
temp = theTemp;
hum = theHum;
pres = thePres;
mChanged();
}
}
ForecastDisplay.java
import java.util.Observable;
import java.util.Observer;
public class ForecastDisplay implements Observer {
private float cPressure;
public float getCPressure() {
return cPressure;
}
private float lPressure;
public float getLPressure() {
return lPressure;
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

public ForecastDisplay(Observable observable) {


observable.addObserver(this);
}
public void update(Observable observable, Object arg) {
if (observable instanceof WeatherData) {
WeatherData weatherData = (WeatherData) observable;
lPressure = cPressure;
cPressure = weatherData.getPressure();
display();
}
}
public void display() {
System.out.println("Forecast");
if (cPressure > lPressure) {
System.out.println("Improving weather on the Way");
} else if (cPressure == lPressure) {
System.out.println("Weather is more of the same");
} else if (cPressure < lPressure) {
System.out.println("Weather out for color, rainy weather");
}
}
}
CurrentConditionDisplay.java
import java.util.Observable;
import java.util.Observer;
public class CurrentConditionDisplay implements Observer {
private float temperature;
private float humidity;
Observable observable;
public CurrentConditionDisplay(Observable observable){
this.observable=observable;
observable.addObserver(this);
}
public void update(Observable o, Object arg) {
if(o instanceof WeatherData){
WeatherData weatherData=(WeatherData)o;
this.temperature=weatherData.getTemperature();
this.humidity=weatherData.getHumidity();
display();
}
}
public void display()
{
Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

System.out.println("Current Condition : " + temperature


+ "F degree and "+ humidity + "humidity");
}
}
client.java
public class client
{
public static void main(String args[])
{
WeatherData weatherData=new WeatherData();
CurrentConditionDisplay ccd=new CurrentConditionDisplay(weatherData);
ForecastDisplay fd=new ForecastDisplay(weatherData);
weatherData.setMeasurements(40.5f, 5.0f, 3.85f);
weatherData.setMeasurements(40.5f, 5.0f, 3.85f);
weatherData.setMeasurements(60.5f, 35.0f, 2.45f);
weatherData.setMeasurements(70.5f, 61.0f, 3.45f);
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:Forecast
Improving weather anyway! Current conditions: 40.5 F Degrees and 5.0% Humidity
Forecast
Cool, rainy weather anyway! Current conditions: 40.5 F Degrees and 5.0% Humidity
Forecast
Current conditions: 70.0 F Degrees and61.0% Humidity

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

3. Forwarder-Receiver
Intent:The Forwarder-Receiver design pattern provides transparent inter-process
communication for software systems with a peer-to-peer interaction model. It introduces
forwarder and receivers to decouple peers from the underlying communication mechanisms.
Description:
Forwarder-Receiver has Distributed peers collaborate to solve a particular 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 peer by encapsulating all system specific functionality into separate components.
Example:
A simple peer-to-peer message exchange scenario; Underlying communication
protocol is TCP/IP.
Participants:
Peer: Server
Receiver: Receiver
Forwarder: Forwarder

Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:-

Class Diagram:-

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Entry.java
class Entry
{
private String destinationId;
private int portNr;
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;
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());
Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

oStr = s.getOutputStream();
oStr.write(data);
oStr.flush() ;
oStr.close();
s.close() ;
}
catch(IOException e)
{
System.out.println("Forerror"+e);
}
}
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
{
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
Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

{
Entry entry = reg.get(myName) ;
srvS = new ServerSocket(entry.port());
System.out.println("Server started");
}
catch(Exception e)
{
e.printStackTrace();
}
}
private Message unmarshal (byte [] anarray)
{
return new Message(myName,new String(anarray));
}
private byte[] receive()
{
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()) ;
}
private void IPCmsg()
{}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Registry.java
import java.util.*;
class Registry //destination and port numbers are entered
{
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"," I am Bhavyasree");
f . sendMsg ("Server", msg) ;
result = r. receiveMsg ( );
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();
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:Server opened.
Marshalling.
Unmarshalling.
I am Bhavyasree

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

5. Proxy
Intent:
Provide a surrogate or placeholder for another object to control access to it. Also
Know as: Surrogate.
Description:
A proxy is:
1. A person authorized to act for another person.
2. An agent or substitute.
3. The authority to act for another .There is situation in which a client does not or
cannot reference an object directly, but wants to still interact with the object
A proxy object can act as the intermediary between the client and 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 target as required. In effect the proxy object has
the authority the act on behalf of client to interact with the target object.
Example:
The client (Client) communicate with a representative (ProxyImage) rather than the
component (RealImage) itself. This representative-called a proxy-offers the interface of
the component but performs additional pre processing and post processing such as accesscontrol checking or making read-only copies of the original.
Participants:
Proxy:ProxyImage
Subject:Image
RealSubject: RealImage

Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:

Class Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Image.java
import java.util.*;
interface Image {
public void displayImage();
}
RealImage.java
public class RealImage implements Image
{
private String filename;
public RealImage(String filename)
{
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk()
{
System.out.println("Loading " + filename);
}
public void displayImage()
{
System.out.println("Displaying " + filename);
}
}
ProxyImage.java
class ProxyImage implements Image {
private String filename;
private Image image;
public ProxyImage(String filename) {
this.filename = filename;
}
public void displayImage() {
image = new RealImage(filename);
image.displayImage();
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

ProxyExample.java
public class ProxyExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
Image image1 = new ProxyImage("High Resolution Image_1 of 25MB");
Image image2 = new ProxyImage("Low Resolution Image_2 of 30kb");
image1.displayImage(); // loading necessary
image2.displayImage(); // loading necessary
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:
Loading High Resolution Image_1 of 25MB
Displaying High Resolution Image_1 of 25MB
Loading Low Resolution Image_2 of 30kb
Displaying Low Resolution Image_2 of 30kb

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

6. Whole-Part
Intent:
The Whole part design pattern helps with the aggregation of components that together
form a semantic unit.
An Aggregate component, the Whole, encapsulates its constituent components, the
Parts, organizes their collaboration, and provides a common interface to its
functionality .Direct access to the Parts is not possible.

Description:
Compose objects into tree structures to represent whole-part hierarchies. Composite
lets clients treat individual objects and compositions of objects uniformly. Application needs
to manipulate a hierarchical collection of primitive and composite objects. Processing of
a primitive object is handled one way, and processing of a composite object is handled
differently.
Example:
The example implements a graphic class, which can be either an ellipse or a
composition of several graphics. Every graphic can be printed. It declares operations, like
Draw() here, that are specific to the object family. It also declares operations that all
composite object share, such operations for accessing and managing its children, like
Add(Graphic).
Participants:
Component:Graphic
Operation:draw
Leaf:Ellipse
Composite:CompositeGraphic
Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:

Class Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Graphic.java
public abstract class Graphic
{
public abstract void draw();
}
Ellipse.java
public class Ellipse extends Graphic
{
public void draw()
{
System.out.println("Ellipse");
}
}

CompositeGraphic.java
import java.util.LinkedHashSet;
import java.util.Set;
public class CompositeGraphic extends Graphic
{
private Set<Graphic> parent;
public CompositeGraphic()
{
parent = new LinkedHashSet<Graphic>();
}
public void draw()
{
for(Graphic i: parent)
{
i.draw();
}
}
public void add(Graphic a)
{
parent.add(a);
}
}
Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Client.java
public class Client
{
public static void main(String args[])
{
Ellipse e1=new Ellipse();
Ellipse e2=new Ellipse();
Ellipse e3=new Ellipse();
Ellipse e4=new Ellipse();
CompositeGraphic g=new CompositeGraphic();
CompositeGraphic g1=new CompositeGraphic();
CompositeGraphic g2=new CompositeGraphic();
g1.add(e1);
g1.add(e2);
g1.add(e3);
g2.add(e4);
g.add(g1);
g.add(g2);
g.draw();
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:
Ellipse
Ellipse
Ellipse
Ellipse

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

7. MASTER-SLAVE
Intent:

Support Fault tolerance, parallel computation and accuracies.


A master component distributes to identical slave component and compute final result
from the slave.

Description:
Divide and Conquer is a common principle for solving many kinds of problems.
Work is partitioned into several equal sub-tasks that are processed independently. The result
of the whole Calculation is computed from the results provided by each partial process.
Several forces arise when implementing such a structure.
Example:
A master component divides work into equal sub-tasks, delegates these subtasks to
several independent but semantically-identical slave components, and computes a final result
from the partial results the slaves return.
Participants:
Master:master
Slave:slave
Use Case Diagram:

Pattern Instance:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Class Diagram:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

master.java
import java.util.Set;
public class master
{
private slave slave;
public static void main(String[] args)
{
master m= new master();
m.run();
}
public void run()
{
slave=new slave();
slave.start();
while(slave.isAlive())
{}
System.out.println("MASTER EXITING....");
}
}
slave.java
public class slave extends Thread
{
public void run()
{
// be cooperative:
try
{
System.out.println("SLAVE IS IN PROCESS");
Thread.sleep(1000);
System.out.println("SLAVE PROCESSING DONE");
} // sleep for 1 sec.
catch(Exception e) {}
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:
SLAVE IS IN PROCESS
SLAVE PROCESSING DONE
MASTER EXITING....

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

4. Client-Dispatcher-Server

Intent:
The client-dispatcher-server provides transparent inter- process communication when
the distributions of component not known at compile time and many vary at run time.
The client dispatcher server pattern introduces an intermediate layer between clients
and server that is the dispatcher component.
It provides location transparency by means of name service, and hides the details of
establishment of the communication connection between clients and servers.
Description:
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.
Example:
The Client-Dispatcher-Server Design Pattern separates the core functionalities from
the code to establish connection and most important it provides location transparency i.e.
the client should not need to know the location of servers.
Participants:
Client:Client
Server:Service
Dispatcher:Dispatcher

Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:

Class Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

CDSMainApp.java
import java.io.*;
import java.lang.*;
public class CDSMainApp
{
public static void main(String [] args)
{
Client c=new Client();
c.dotask();
}
}
Client.java
import java.io.*;
public class Client
{ private PrintService print;
private Dispatcher dis=new Dispatcher();
public PrintService thePrintserver;
public Client()
{}
public void dotask()
{
dis.request_channel();
dis.establish_channel();
}
}
Dispatcher.java
import java.io.*;
public class Dispatcher
{
private Client client;
private PrintService print=new PrintService();
public Dispatcher()
{ }
public void establish_channel()
{
System.out.println("ESTABLISHED CHANNEL SUCCESSFULLY!!!");
print.runservice();
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

public void request_channel()


{
System.out.println("REGISTERED CHANNEL SUCESSFULLY!!!!");
}
}

PrintService.java
import java.io.*;
public class PrintService
{
private Service server1=new Service();
private Client client;
private Dispatcher dis;
public PrintService()
{ }
public void runservice()
{
server1.runservice();
}
}
Service.java
import java.io.*;
public class Service
{
public Service()
{}
public void runservice()
{
System.out.println("SERVICE IS PROVIDED!!! ");
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

OUTPUT:
REGISTERED CHANNEL SUCESSFULLY!!!!
ESTABLISHED CHANNEL SUCCESSFULLY!!!
SERVICE IS PROVIDED!!!

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

2. Command Processor
Intent:
System management.
System need to handle collections of objects.
For example, events from other systems that needs to be interpreted and scheduled.
A command processor component manages requests as separate objects, schedules their
execution, and provides additional services such as the string of request objects for later
undo.
Description:
The command processor design pattern separates the request for service from its
execution.
A command processor component manages request as separate objects, schedules their
execution and provides additional service
Example:
A Stock Exchange where a client want to Buy or sell a stock , he has to done through
Agent. Agent will buy or sell stock from stack trade behalf of client.
Participants:
Command:Order
ConcreteCommand:BuyOrder,SellStockOrder
Client:Client
Invoker:Agent
Receiver:StockTrade
ConcreteCommandReceiver:buyStockOrder,sellStockOrder

Use Case Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Pattern Instance:

Class Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Sequence Diagram:

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Agent.java
public class Agent
{
private Order order;
public StockTrade st=new StockTrade();
public Order getOrder()
{
return order;
}
public void setOrder(Order theOrder){ }
public void placeOrder(int i)
{
st.buy();
}
public void placeOrder1(int i)
{
st.sell();
}
public void invokeOrder(){ };
}
BuyStockOrder.java
public class BuyStockOrder implements Order {
private StockTrade stock;
public BuyStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock.buy();
}
}
Client.java
public class Client {
public static void main(String[] args) {
StockTrade stock = new StockTrade();
BuyStockOrder bsc = new BuyStockOrder (stock);
SellStockOrder ssc = new SellStockOrder (stock);
Agent agent = new Agent();
agent.setOrder(bsc);
agent.setOrder(ssc);
agent.placeOrder(12); // Buy Shares
agent.placeOrder1(134); // Sell Shares
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Order.java
public interface Order {
public abstract void execute ( );
}
SellStockOrder.java
public class SellStockOrder implements Order {
private StockTrade stock;
public SellStockOrder ( StockTrade st) {
stock = st;
}
public void execute( ) {
stock . sell( );
}
}
StockTrade.java
public class StockTrade {
public void buy() {
System.out.println("CUSTOMER BUYING STOCKS");
}
public void sell() {
System.out.println("CUSTOMER SELLING STOCKS");
}
}

Department of Computer Applications

BMS College of Engineering

10MCA56 : Software Design Laboratory

Page No.:

Output:
CUSTOMER BUYING STOCKS
CUSTOMER SELLING STOCKS

Department of Computer Applications

BMS College of Engineering

S-ar putea să vă placă și