Вы находитесь на странице: 1из 44

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 concreteSubject : WeatherData
ConcreteObserver: CurrentConditionDisplay, ForecastDisplay

Usecase Diagram:

Pattern Instance:

Class diagram:

Sequence Diagram:

Java Code:
WeatherData.java:
import java.util.Observable;
public class WeatherData extends Observable
{
private float temperature;
public float getTemperature()
{
return temperature;
}
private float pressure;
public float getPressure()
{
return pressure;
}
private float humidity;
public float getHumidity()
{
return humidity;
}
public void measurementschanged()
{
setChanged();
notifyObservers();
}
public void setMeasurements(float theTemperature, float theHumidity, float thePressure)
{
temperature=theTemperature;
pressure=thePressure;
humidity=theHumidity;
measurementschanged();
}
}

ForeCastDisplay.java:
import java.util.Observable;
import java.util.Observer;
public class ForeCastDisplay implements Observer
{
private float currentPressure = 29.92f;

private float 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!");
}
else if (currentPressure == lastPressure)
{
System.out.println("More of the same");
}
else if (currentPressure < lastPressure)
{
System.out.println("Watch out for cooler, rainy weather");
}
}
}

CurrentConditionDisplay.java
import java.util.Observable;
import java.util.Observer;
public class CurrentConditionDispaly implements Observer
{
private float temperature;
private float humidity;
Observable observable;
public CurrentConditionDispaly(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.getTemperature();
this.humidity = weatherData.getHumidity();
display();
}
}
public void display()
{
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}

Client.java
public class WeatherStation
{
public static void main(String[] args)
{
WeatherData weatherData = new WeatherData();
CurrentConditionDispaly currentConditions = new
CurrentConditionDispaly(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 and 65.0% humidity
Forecast: Watch out for cooler, rainy weather
Current conditions: 82.0F degrees and 70.0% humidity
Forecast: More of the same
Current conditions: 78.0F degrees and 90.0% humidity

2. Command Design Pattern

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class _switch extends JFrame{
JTextField jtf=new JTextField(10);
JLabel jlb=new JLabel("sentence");
_switch()
{
Container container=getContentPane();
container.setLayout(new FlowLayout());
JButton button1=new JButton("bold");
JButton button2=new JButton("capitalize");
JButton button3=new JButton("undo");
container.add(jlb);
container.add(jtf);
container.add(button1);
container.add(button2);
container.add(button3);

Font f=jtf.getFont();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button1.addActionListener(new receiver(jtf,f));
button2.addActionListener(new receiver(jtf,f));
button3.addActionListener(new receiver(jtf,f));
}
public static void main(String args[])
{
_switch dt=new _switch();
dt.setSize(500, 500);
dt.setVisible(true);
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Set;

public class receiver implements ActionListener{


JTextField jtf;
Font f;
receiver(JTextField ob,Font f1)
{
jtf=ob;
f=f1;
}
public void actionPerformed(ActionEvent ae)
{
String show=jtf.getText();
if(ae.getActionCommand().equals("bold"))
jtf.setFont(new Font("Dialog",Font.BOLD,15));
else if (ae.getActionCommand().equals("capitalize"))
jtf.setText(jtf.getText().toUpperCase());
else
{jtf.setText(jtf.getText().toLowerCase());
jtf.setFont(f);

}
}}

3. Forwarder Receiver Design Pattern


Context: Peer-to-Peer communication.
Problem: A common way to build distributed applications is to make use of available low-level
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.

Usecase Diagram:

Activity Diagram:

Pattern instance:

Class Diagram:

Client

Entry
ipa : String
portno : int

main()
Forwarder
Forwarder()

Register
htable : Hashtable
put()
get()

Entry()
ipadd()
port()

Receiver
main()

Sequence Diagram:

Java Code:
Client.java
class Client
{
static Register reg=new Register();
public static void main(String arg[])throws Exception
{
Entry entry=new Entry("127.0.0.1",1600);
reg.put("server",entry);
String msg="hello server";
Forwarder f=new Forwarder("server",reg,msg);
}
}

Entry.java
class Entry
{
String ipa;

int portno;
public Entry(String ip,int port)
{
ipa=ip;
portno=port;
}
public String ipadd()
{
return ipa;
}
public int port()
{
return portno;
}
}

Forwarder.java

import java.net.*;
import java.util.*;
import java.io.*;
public class Forwarder
{
public Forwarder(String name,Register reg,String msg)throws Exception
{
String data=null;
Entry entry=reg.get(name);
Socket skt= new Socket(entry.ipadd(),entry.port());
System.out.println(msg);
InputStream is=skt.getInputStream();
OutputStream os=skt.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
dos.writeUTF(msg);
data=dis.readUTF();
System.out.println(data);
}
}

Receiver.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Receiver
{
public static void main(String args[])throws IOException
{
String data=null;
ServerSocket sskt=new ServerSocket(1600);
System.out.println("Server Starded......................");
Socket skt=sskt.accept();

InputStream is=skt.getInputStream();
OutputStream os=skt.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
data=dis.readUTF();
dos.writeUTF("hi,how are you");
System.out.println("Response Sucessful");
}
}

Register.java
import java.util.*;
class Register
{
Hashtable htable=new Hashtable();
public void put(String name,Entry ent)
{
htable.put(name,ent);
}
public Entry get(String key)
{
return (Entry)htable.get(key);
}
}

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.
The static relationships between clients, servers and the dispatcher are as follows:
Usecase Diagram:

Activity Diagram:

Pattern Instance:

Class diagram:

Sequence Diagram:

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

Dispatcher.java:
import java.util.*;
import java.io.*;
class NotFound extends Exception {}
public class Dispatcher
{
private Client client;
private PrintService printservice;
Hashtable registry = new Hashtable();
Random rnd = new Random(123456);
public void registerService(String svc, Service obj)
{
Vector v = (Vector) registry. get (svc) ;
if (v == null)
{
v = new Vector ();
registry.put (svc, v) ;
}
v.addElement(obj);
}
public void unregisterService()
{
}
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();


int i = rnd.nextInt () % v.size() ;
return (Service) v. elementAt (i) ;
}
public void establishChannel()
{
}
public void getChannel()
{
}
}

Service.java:
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() ;
}

PrintService.java :
public 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);
}
public void receiveRequest()

{
}

Client.java:
public class Client
{
private Dispatcher dispatcher;
private PrintService printservice;
public void doTask()
{
Service s;
try
{
s = CDS .disp. locateServer ("printSvc1") ;
s . runService ( ) ;
}
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") ;
}
}
public void sendRequest()
{
}
}

Output:

Service printSvc1 by srvl


Service printSvc2 by srv2
Not available

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:

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.
UseCase Diagram:

Pattern Instance:

Class Diagram:

Sequence Diagram :

Communication Diagram:

Java Code :
EMailService.java:
public interface EMailService
{
public void sendMail(String receiver, String subject, String text);
public void receiveMail(String receiver);
}

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

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

}
}

Application.java:
public class Application
{
public EMailService locateEMailService()
{
EMailService emailService = new ProxyEMailService();
return emailService;
}
}

ApplicationClient.java:
public class ApplicationClient
{
public static void main(String[] args)
{
Application application = new Application();
EMailService emailService = application.locateEMailService();
emailService.sendMail("abc@gmail.com", "Hello", "A test mail");
emailService.receiveMail("abc@gmail.com");
}
}

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

6. Whole-Part Design Pattern


Class Diagram

Client

WholeGraphics
Graphics

Ellipse

Interaction Diagram

: Ellipse

: Client

: WholeGraphics

initialize ellipse
initialize whole graphics

compose the graphics

print the complete graphics

Use-Case Diagram

Ellipse
Initialize ellipse

Initialize Composite Graphics

Client

Compose Graphics

Print complete Graphic

WholeGraphics

import java.util.List;
import java.util.ArrayList;
/** "Component" */
interface Graphic {
//Prints the graphic.
public void print();
}
/** "Whole" */
class WholeGraphic implements Graphic {
//Collection of child graphics.
private List<Graphic> childGraphics = new ArrayList<Graphic>();
//Prints the graphic.
public void print() {
for (Graphic graphic : childGraphics) {
graphic.print();
}
}

//Adds the graphic to the composition.


public void add(Graphic graphic) {
childGraphics.add(graphic);
}
//Removes the graphic from the composition.
public void remove(Graphic graphic) {
childGraphics.remove(graphic);
}
}

class Ellipse implements Graphic {


//Prints the graphic.
public void print() {
System.out.println("Ellipse");
}
}
/** Client */
public class Client {
public static void main(String[] args) {
//Initialize four ellipses
Ellipse ellipse1 = new Ellipse();
Ellipse ellipse2 = new Ellipse();
Ellipse ellipse3 = new Ellipse();
Ellipse ellipse4 = new Ellipse();

WholeGraphic graphic = new WholeGraphic();


WholeGraphic graphic1 = new WholeGraphic();
WholeGraphic graphic2 = new WholeGraphic();
graphic1.add(ellipse1);
graphic1.add(ellipse2);
graphic1.add(ellipse3);
graphic2.add(ellipse4);
graphic.add(graphic1);
graphic.add(graphic2);
//Prints the complete graphic (four times the string "Ellipse").
graphic.print();
}
}

7. Master-Slave Design Pattern

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


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;
}
TestMaster.java

public class TestMaster {


private Resource resource;
public Resource getResource() {
return resource;
}
public void setResource(Resource theResource) {
resource = theResource;
}
public static void main(String args[]) {
Master ms=new Master();
ms.run();
}
}

Вам также может понравиться