Software Design Manual 2013

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 65

10MCA56

Software Design Laboratory

1RN11MCA01

Choose Workspace folder

Select Workbench

Dept. Of MCA

RNSIT

Page 1

10MCA56

Software Design Laboratory

1RN11MCA01

Set Modeling

Creating a New UML Project

Dept. Of MCA

RNSIT

Page 2

10MCA56

Software Design Laboratory

1RN11MCA01

Enter the Project Name and Click Next

Dept. Of MCA

RNSIT

Page 3

10MCA56

Software Design Laboratory

1RN11MCA01

Select Blank Model, give Proper name and Click Finish

Created UML Project details displayed on Project Explorer

Dept. Of MCA

RNSIT

Page 4

10MCA56

Software Design Laboratory

1RN11MCA01

To Find Pattern Explorer

Search for pattern Select Pattern Explorer


Click OK

Dept. Of MCA

RNSIT

Page 5

10MCA56

Software Design Laboratory

1RN11MCA01

Creating Pattern Instance


Select the required pattern from Pattern Explorer

Drag and drop on model Main screen

Dept. Of MCA

RNSIT

Page 6

10MCA56

Software Design Laboratory

1RN11MCA01

Pass the arguments

Create Class Diagram


Right click on Model -> Select Add Diagram -> Select Class Diagram

Dept. Of MCA

RNSIT

Page 7

10MCA56

Software Design Laboratory

1RN11MCA01

Drag & drop the arguments created for Pattern instance on Class diagram

Pass the required Attributes and Operations

Dept. Of MCA

RNSIT

Page 8

10MCA56

Dept. Of MCA

Software Design Laboratory

RNSIT

1RN11MCA01

Page 9

10MCA56

Software Design Laboratory

1RN11MCA01

Transformation from UML to Java


Go to Modeling -> Select Transform -> New Configuration

Give a name for Transformation file and select transformation UML to Java V5.0
Click Next

Dept. Of MCA

RNSIT

Page 10

10MCA56

Software Design Laboratory

1RN11MCA01

Select the UML model to transform


Click on Create New Target Container

Give name to Target Java Project and Click Finish

Dept. Of MCA

RNSIT

Page 11

10MCA56

Software Design Laboratory

1RN11MCA01

Uncheck the Check box Generate getter and setters


Click Finish

Dept. Of MCA

RNSIT

Page 12

10MCA56

Software Design Laboratory

1RN11MCA01

Right click on Transformation file and Select Transform UML to Java V5.0

Dept. Of MCA

RNSIT

Page 13

10MCA56

Software Design Laboratory

1RN11MCA01

Define the methods in Java classes generated and make it as executable code by adding a class with
main() method.
Right click on Class with main( ) method Select Run As -> Java Application

Check the Output on Console

Dept. Of MCA

RNSIT

Page 14

10MCA56

Software Design Laboratory

1RN11MCA01

Creating Use-case Diagram

Dept. Of MCA

RNSIT

Page 15

10MCA56

Software Design Laboratory

1RN11MCA01

Creating Sequence Diagram

Creating Activity Diagram

Dept. Of MCA

RNSIT

Page 16

10MCA56

Software Design Laboratory

1RN11MCA01

Creating Component Diagram

Dept. Of MCA

RNSIT

Page 17

10MCA56

Software Design Laboratory

1RN11MCA01

Reverse Transformation (Java to UML)


Create a Java Project

Dept. Of MCA

RNSIT

Page 18

10MCA56

Software Design Laboratory

1RN11MCA01

Give name for Java Project and Click Finish

Right Click on Java project -> Select New -> Select Package

Dept. Of MCA

RNSIT

Page 19

10MCA56

Software Design Laboratory

1RN11MCA01

Give the package name and Click Finish

Right click on package Select New -> Select Class

Dept. Of MCA

RNSIT

Page 20

10MCA56

Software Design Laboratory

1RN11MCA01

Give name for Class and Click Finish

Define the class created

Dept. Of MCA

RNSIT

Page 21

10MCA56

Software Design Laboratory

1RN11MCA01

To create a Class with main() method


Right click on package Select New -> Select Class

Give name for Class, select the Check box public static void main(String[] args) and Click Finish

Dept. Of MCA

RNSIT

Page 22

10MCA56

Software Design Laboratory

1RN11MCA01

Define the methods in classes created.


To Transform from Java to UML

Go to Modeling -> Select Transform -> New Configuration

Give a name for Transformation file and select transformation Java to UML.

Dept. Of MCA

RNSIT

Page 23

10MCA56

Software Design Laboratory

1RN11MCA01

Select Java project as Source and Click on Create New Target Container

Select Standard template and Click Next


Select Blank Model and Container folder and Click Finish

Dept. Of MCA

RNSIT

Page 24

10MCA56

Software Design Laboratory

1RN11MCA01

Publisher Subscriber design pattern


Context: A component uses data or information provided by another component.
Problem: Changing the internal state of a component may introduce
inconsistencies between cooperating components. Two forces associated with this
problem are:
The components should be loosely coupled.
The components that are depends on the information provider are not known
a priori.
Solution: Implement a Change-Propagation mechanism between the information
provider Subject and the components dependent on it observers. Observers can
dynamically register or unregister with this mechanism.
Whenever the subject changes its state, changes are propagated by invoking a
special update ( ) function common to all observers.
Pattern Instance

Class diagram

Dept. Of MCA

RNSIT

Page 25

10MCA56

Software Design Laboratory

1RN11MCA01

Use Case Diagram

Sequence Diagram

Dept. Of MCA

RNSIT

Page 26

10MCA56

Software Design Laboratory

1RN11MCA01

Activity diagram

Implementation
Mclass.java
public class Mclass
{
public static void main(String[] args)
{
Furnace fr=new Furnace();
CurrentTemp ct=new CurrentTemp();
DisplayTemp dt=new DisplayTemp();
fr.addObserver(ct);
fr.addObserver(dt);
fr.setTemp(56);
fr.setTemp(6);
}
}

Dept. Of MCA

RNSIT

Page 27

10MCA56

Software Design Laboratory

1RN11MCA01

Furnace.java
import java.util.Observable;
public class Furnace extends Observable
{
public int temp;
public void setTemp(int a)
{
temp=a;
setChanged();
notifyObservers(temp);
}
}
CurrentTemp.java
import java.util.Observable;
import java.util.Observer;
public class CurrentTemp implements Observer
{
public void update(Observable o, Object arg)
{
int t=(Integer)arg;
System.out.println("The current temperature is "+t);
}
}
DisplayTemp.java
import java.util.Observable;
import java.util.Observer;
public class DisplayTemp implements Observer
{
public void update(Observable o, Object arg)
{
int t=(Integer)arg;
if(t>35)
System.out.println("Temperature is High");
else if(t<10)
System.out.println("Temperature is low");
else
System.out.println("Temperature is moderate");

Dept. Of MCA

RNSIT

Page 28

10MCA56

Software Design Laboratory

1RN11MCA01

}
}

Output:
Temperature is High
The current temperature is 56
Temperature is low
The current temperature is 6

Dept. Of MCA

RNSIT

Page 29

10MCA56

Software Design Laboratory

1RN11MCA01

Command Processor design pattern


Context: Applications that need flexible and extensible user interfaces or
applications that provide services related to the execution of user functions.
Problem: Applications supports different modes of user interaction. We often need
to implement services that go beyond the core functionality such as redo, undo etc.
The forces are
Different users like to work with application in different ways.
Enhancements of the application should not break existing code.
Additional services such as undo should be implemented consistently for all
services.
Solution: The central component Command Processor that takes care of all
command objects. It 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.
Class Diagram

Dept. Of MCA

RNSIT

Page 30

10MCA56

Software Design Laboratory

1RN11MCA01

Use Case Diagram

Sequence Diagram

Dept. Of MCA

RNSIT

Page 31

10MCA56

Software Design Laboratory

1RN11MCA01

Component diagram

Implementation
Command.java
public interface Command
{
public void execute();
public void unExecute();
}
CommandProcessor.java
package cmdprocessor;
import java.util.ArrayList;
public class CommandProcessor
{
private BoldAndUpper boldandupper=new BoldAndUpper();
private ArrayList<Command> commands=new ArrayList<Command>();
private int current=0;
public void redo(int levels)
{
System.out.println("\n---- Redo "+levels+" levels ----");
for(int i=0;i<levels;i++)
{
if(current < commands.size())

Dept. Of MCA

RNSIT

Page 32

10MCA56

Software Design Laboratory

1RN11MCA01

{
Command cmd=commands.get(current++);
cmd.execute();
}
}
}
public void undo(int levels)
{
System.out.println("\n---- Undo "+levels+" levels ----");
for(int i=0;i<levels;i++)
{
if(current > 0)
{
Command cmd=commands.get(--current);
cmd.unExecute();
}
}
}
public void compute(String operator)
{
Command cmd=new BoldAndUpperCommand(boldandupper,operator);
cmd.execute();
commands.add(cmd);
current++;
}
}
BoldAndUpper.java
public class BoldAndUpper
{
private String curenttask = "";
public void operation(String operator)
{
if(operator=="bold")
{
curenttask="BOLD";
}
if(operator=="undobold")
{
curenttask="undo bold";
}
if(operator=="uppercase")
{

Dept. Of MCA

RNSIT

Page 33

10MCA56

Software Design Laboratory

1RN11MCA01

curenttask="UPPER CASE";
}
if(operator=="undouppercase")
{
curenttask="undo upper case";
}
System.out.println("Current value= "+curenttask+" - after "+operator);
}
}
BoldAndUpperCommand.java
public class BoldAndUpperCommand implements Command
{
private String operator;
private String text;
private BoldAndUpper bolandupper;
public BoldAndUpperCommand(BoldAndUpper bolandupper,String operator)
{
this.bolandupper=bolandupper;
this.operator=operator;
this.text=text;
}
public void execute()
{
bolandupper.operation(operator);
}
public void unExecute()
{
bolandupper.operation(undo(operator));
}
private String undo(String operator)
{
String undo="";
if(operator=="bold")
{
undo="undobold";
}
else if(operator=="uppercase")
{
undo="undouppercase";
}

Dept. Of MCA

RNSIT

Page 34

10MCA56

Software Design Laboratory

1RN11MCA01

else
{
undo="";
}
return undo;
}
}

MainClass.java
public class MainClass
{
public static void main(String[] args)
{
CommandProcessor cp=new CommandProcessor();
cp.compute("bold");
cp.compute("uppercase");
cp.undo(1);
cp.redo(2);
}
}

Output:
Current value= BOLD - after bold
Current value= UPPER CASE - after uppercase
---- Undo 1 levels ---Current value= undo upper case - after undouppercase
---- Redo 2 levels ---Current value= UPPER CASE - after uppercase

Dept. Of MCA

RNSIT

Page 35

10MCA56

Software Design Laboratory

1RN11MCA01

Forwarder-Receiver design pattern


Context: Peer to Peer communication.
Problem: Building distributed applications using low level mechanisms for interprocesses communication such as TCP/IP, sockets or Message Queues are efficient
but not portable. It constraints the systems capability to support heterogeneous
environments and makes it hard to change the IPC mechanism later. The forces are
The system should allow the exchangeability of the communication
mechanisms.
The cooperation of components follows a peer to peer model, in which
sender needs to know the names of its receivers.
The communication between the peers should not have a major impact on
performance.
Solution: A Peer may act as a client, requesting services, as a server, providing
services or both. The details of sending and receiving messages are hidden from
Peer by encapsulating all system specific functionality into separate components
forwarder and receiver.

Pattern Instance

Dept. Of MCA

RNSIT

Page 36

10MCA56

Software Design Laboratory

1RN11MCA01

Class diagram

Use Case Diagram

Dept. Of MCA

RNSIT

Page 37

10MCA56

Software Design Laboratory

1RN11MCA01

Sequence Diagram

Component diagram

Dept. Of MCA

RNSIT

Page 38

10MCA56

Software Design Laboratory

1RN11MCA01

Implementation
Peer.java
package frpackage;
public class Peer
{
public Receiver varreceiver;
public Forwarder varforwarder;
public String varname;
public Forwarder theForwarder;
public Receiver theReceiver;
public Peer(String str)
{
varname=str;
}
public Receiver getReceiver()
{
return varreceiver;
}
public void setReceiver(Receiver theReceiver)
{
varreceiver=theReceiver;
}
public Forwarder getForwarder()
{
return varforwarder;
}
public void setForwarder(Forwarder theForwarder)
{
varforwarder=theForwarder;
}
public void service(String msg,Peer dest)
{
System.out.println("Sending Msg: "+ dest);
System.out.println("Msg: "+msg);
this.varforwarder.sendMsg(msg, dest, this);
}

Dept. Of MCA

RNSIT

Page 39

10MCA56

Software Design Laboratory

1RN11MCA01

public static void main(String args[])


{
Forwarder f1=new Forwarder();
Forwarder f2=new Forwarder();
Receiver r1=new Receiver();
Receiver r2=new Receiver();
Peer p1=new Peer("Peer1");
p1.setForwarder(f1);
p1.setReceiver(r1);
Peer p2=new Peer("Peer2");
p2.setForwarder(f2);
p2.setReceiver(r2);
p1.service("Its Peer1",p2);
}
}
Forwarder.java
package frpackage;
public class Forwarder
{
private Peer varpeer;
private Receiver varreceiver;
public Peer thePeer;
public Receiver theReceiver;
public Peer getPeer()
{
return varpeer;
}
public void setPeer(Peer thePeer)
{
varpeer=thePeer;
}
public Receiver getReceiver()
{
return varreceiver;
}
public void setReceiver(Receiver theReceiver)
{
varreceiver=theReceiver;

Dept. Of MCA

RNSIT

Page 40

10MCA56

Software Design Laboratory

1RN11MCA01

}
public void sendMsg(String msg,Peer dest,Peer src)
{
Receiver r=dest.getReceiver();
r.receiveMsg(msg,src);
}
}
Receiver.java
package frpackage;
public class Receiver
{
private Peer varpeer;
private Forwarder varforwarder;
public Peer thePeer;
public Forwarder theForwarder;
public void receiveMsg(String m,Peer src)
{
System.out.println("msg received from: "+src);
System.out.println("msg: "+m);
}
public void setForwarder(Forwarder theForwarder)
{
varforwarder=theForwarder;
}
public Forwarder getForwarder()
{
return varforwarder;
}
public void setPeer(Peer thePeer)
{
varpeer=thePeer;
}
public Peer getPeer()
{
return varpeer;
}
}

Dept. Of MCA

RNSIT

Page 41

10MCA56

Software Design Laboratory

1RN11MCA01

Output:
Sending Msg: frpackage.Peer@34f034f0
Msg: Its Peer1
msg received from: frpackage.Peer@34e834e8
msg: Its Peer1

Dept. Of MCA

RNSIT

Page 42

10MCA56

Software Design Laboratory

1RN11MCA01

Client Dispatcher Server design pattern


Context: A software system integrating a set of distributed servers, with the
servers running locally or distributed over a network.
Problem: A connection between components may have to be established before
the communication can take place, depending on available communication
facilities. Clients should not know where servers are located. The forces are:
A component should be able to use a service independent of the location of
the service provider.
The code implementing the functional core of a service consumer should be
separate from the code used to establish a connection with service providers.
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. In addition, the
dispatcher is responsible for establishing the communication channel between
client and server.

Pattern Instance

Dept. Of MCA

RNSIT

Page 43

10MCA56

Software Design Laboratory

1RN11MCA01

Class diagram

Use Case Diagram

Dept. Of MCA

RNSIT

Page 44

10MCA56

Software Design Laboratory

1RN11MCA01

Sequence Diagram

Component diagram

Dept. Of MCA

RNSIT

Page 45

10MCA56

Software Design Laboratory

1RN11MCA01

Implementation
CDSMain.java
public class CDSMain
{
public static Dispatcher disp=new Dispatcher();
public static void main(String args[])
{
Service s1=new PrintService("PrintService","Printer");
Service s2=new ScanService("Service1","Scanner");
Client client=new Client();
client.doTask();
}
}
Client.java
public class Client
{
public Service s;
public void doTask()
{
try
{
s=CDSMain.disp.locateServer("PrintService");
s.runService();
}
catch(NotFound n)
{
System.out.println("Service not available");
}
try
{
s=CDSMain.disp.locateServer("Service1");
s.runService();
}
catch(NotFound n)
{
System.out.println("Service1 not available");
}

Dept. Of MCA

RNSIT

Page 46

10MCA56

Software Design Laboratory

1RN11MCA01

try
{
s=CDSMain.disp.locateServer("FAXService");
s.runService();
}
catch(NotFound n)
{
System.out.println("Fax service not available");
}
}
}
Dispatcher.java
import java.util.*;
public class Dispatcher
{
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 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);
}
}

Dept. Of MCA

RNSIT

Page 47

10MCA56

Software Design Laboratory

1RN11MCA01

Service.java
public abstract class Service
{
String nameofservice;
String nameofserver;
public Service(String svc, String svr)
{
nameofservice=svc;
nameofserver=svr;
CDSMain.disp.registerService(nameofservice,this);
}
public abstract void runService();
}
PrintService.java
public class PrintService extends Service
{
public PrintService(String svc, String svr)
{
super(svc,svr);
}
public void runService()
{
System.out.println("Service "+nameofservice+" by "+nameofserver);
}
}
ScanService.java
public class ScanService extends Service
{
public ScanService(String svc, String svr)
{
super(svc,svr);
}
public void runService()
{
System.out.println("Service "+nameofservice+" by "+nameofserver);
}
}

Dept. Of MCA

RNSIT

Page 48

10MCA56

Software Design Laboratory

1RN11MCA01

NotFound.java
public class NotFound extends Exception
{
public NotFound()
{
System.out.println("Requested service not Found");
}
}

Output:
Service PrintService by Printer
Service Service1 by Scanner
Requested service not Found
Fax service not available

Dept. Of MCA

RNSIT

Page 49

10MCA56

Software Design Laboratory

1RN11MCA01

Proxy design pattern


Context: A client needs access to the services of another component. Direct access
is technically possible, but may not be the best approach.
Problem: It is often inappropriate to access a component directly. We do not want
to hardcode its physical location into clients, and direct and unrestricted access to
the component may be inefficient and insecure. The forces are
Accessing the component should be runtime efficient, cost-effective and
safe for both the client and the component.
Access to the component should be transparent and simple for the client.
The client should be well aware of possible performances or financial
penalties for accessing remote clients.
Solution: Let the client communicate with the representative rather than the
component itself. This representative called proxy offers the interface of the
component but performs additional pre and post processing such as access-control
checking or making read-only copies of original.

Pattern Instance

Dept. Of MCA

RNSIT

Page 50

10MCA56

Software Design Laboratory

1RN11MCA01

Class diagram

Use Case Diagram

Dept. Of MCA

RNSIT

Page 51

10MCA56

Software Design Laboratory

1RN11MCA01

Sequence Diagram

Component diagram

Dept. Of MCA

RNSIT

Page 52

10MCA56

Software Design Laboratory

1RN11MCA01

Implementation
MyClient.java
public class MyClient
{
public static void main(String[] args)
{
Application app=new Application();
EmailService eserv=app.locateEmailService();
eserv.sendmail("abc@rnsit.ac.in", "Hi", "Test mail");
eserv.receivemail("xyz@rnsit.ac.in");
}
}

Application.java
public class Application
{
public EmailService locateEmailService()
{
System.out.println("Application locate Email Service");
EmailService eserv=new ProxyEmailService();
return eserv;
}
}
EmailService.java
public interface EmailService
{
public void receivemail(String receiver);
public void sendmail(String receiver, String subject, String text);
}
ProxyEmailService.java
public class ProxyEmailService implements EmailService
{
private RealEmailService serviceref;
public void receivemail(String receiver)
{

Dept. Of MCA

RNSIT

Page 53

10MCA56

Software Design Laboratory

1RN11MCA01

if(serviceref==null)
{
serviceref=new RealEmailService();
}
serviceref.receivemail(receiver);
}
public void sendmail(String receiver, String subject, String text)
{
if(serviceref==null)
{
serviceref=new RealEmailService();
}
serviceref.sendmail(receiver, subject, text);
}
}
RealEmailService.java
public class RealEmailService implements EmailService
{
public void receivemail(String receiver)
{
System.out.println("Received Email from: "+receiver);
}
public void sendmail(String receiver, String subject, String text)
{
System.out.println("Sending mail to :-"+receiver+" with subject="+subject);
System.out.println("Content: "+text);
}
}

Output:
Application locate Email Service
Sending mail to :-abc@rnsit.ac.in with subject=Hi
Content: Test mail
Received Email from: xyz@rnsit.ac.in

Dept. Of MCA

RNSIT

Page 54

10MCA56

Software Design Laboratory

1RN11MCA01

Whole-Part design pattern


Context: Implementing aggregate objects.
Problem: In almost every software system objects are composed of other objects
exist. Such aggregated objects do not represent loosely coupled set of components.
Instead they form units that are more than just a collection of their parts. The
combination of parts makes new behaviour emerge. The forces are
A complex object should either be decomposed into smaller objects, or
composed of existing objects, to support reusability, changeability and the
recombination of 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.

Pattern Instance

Dept. Of MCA

RNSIT

Page 55

10MCA56

Software Design Laboratory

1RN11MCA01

Class diagram

Use Case Diagram

Dept. Of MCA

RNSIT

Page 56

10MCA56

Software Design Laboratory

1RN11MCA01

Component diagram

Implementation
MyClient.java
public class MyClient
{
public static void main(String[]args)
{
Leaf b1=new Leaf();
Leaf b2=new Leaf();
leaf1 b11=new leaf1();
leaf2 b21=new leaf2();
leaf2 b22=new leaf2();
Composite c1=new Composite();
Composite c2=new Composite();
Composite c=new Composite();
c1.add(b1);
c1.add(b2);
c1.add(b11);

Dept. Of MCA

RNSIT

Page 57

10MCA56

Software Design Laboratory

1RN11MCA01

c2.add(b21);
c2.add(b22);
c.add(c1);
c.add(c2);
c.assemble();
}
}
Group.java
public abstract class Group
{
public abstract void assemble();
}
Composite.java
import java.util.*;
public class Composite extends Group
{
private List<Group> groups = new ArrayList<Group>();
public void add(Group gp)
{
groups.add(gp);
}
public void assemble()
{
for(Group mygrp : groups)
{
mygrp.assemble();
}
}
}
Leaf.java
public class Leaf extends Group
{
public void assemble()
{
System.out.println("leaf");

Dept. Of MCA

RNSIT

Page 58

10MCA56

Software Design Laboratory

1RN11MCA01

}
}

Leaf1.java
public class Leaf1 extends Group
{
public void assemble()
{
System.out.println("leaf1");
}
}
Leaf2.java
public class Leaf2 extends Group
{
public void assemble()
{
System.out.println("leaf2");
}
}

Output:
leaf
leaf
leaf1
leaf2
leaf2

Dept. Of MCA

RNSIT

Page 59

10MCA56

Software Design Laboratory

1RN11MCA01

Master-Slave design pattern


Context: Partitioning work into semantically identical sub tasks.
Problem: Divide and Conquer is commonly used to solve many 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. The forces are
Clients should not be aware that the calculation is based on the divide and
conquer principle.
Neither clients nor processing of sub tasks should depend on the algorithm
for partitioning work and assembling the final result.
It can be helpful to use different but semantically identical implementations
for processing sub-tasks.
Processing of subtasks sometimes needs coordination.
Solution: Introduce a coordination instance between clients of the service and the
processing of individual sub-tasks.
A master component divides the work into equal sub-tasks, delegates these subtasks to several independent but semantically- identical slave components and
compute a final result from the partial results the slave return.

Pattern Instance

Dept. Of MCA

RNSIT

Page 60

10MCA56

Software Design Laboratory

1RN11MCA01

Class diagram

Use Case Diagram

Dept. Of MCA

RNSIT

Page 61

10MCA56

Software Design Laboratory

1RN11MCA01

Component diagram

Implementation

MyClient.java
public class MyClient
{
public static void main(String[] args)
{
Master mas=new Master();
mas.run();
}
}

Dept. Of MCA

RNSIT

Page 62

10MCA56

Software Design Laboratory

1RN11MCA01

Master.java
public class Master
{
private int slaveCount = 2;
private Resource res = new Resource();
private Slave[] slaves = new Slave[slaveCount];
public void run()
{
for(int i=0;i<slaveCount;i++)
{
slaves[i]=new Slave(res);
slaves[i].start();
try
{
slaves[i].join();
}
catch(Exception ie)
{
System.err.println(ie.getMessage());
}
finally
{
System.out.println(slaves[i].getName() +"has died");
}
}
System.out.println("the master will now die...");
}
}
Slave.java
public class Slave extends Thread
{
private Resource sharedResource;
private boolean done=false;
public Slave(Resource rcs)
{
sharedResource=rcs;
}
protected boolean task()
{
int status = sharedResource.incstatus();

Dept. Of MCA

RNSIT

Page 63

10MCA56

Software Design Laboratory

1RN11MCA01

return (status >= 5);


}
public void run()
{
while(done != true)
{
done=task();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
Resource.java
public class Resource
{
private int status=0;
synchronized int incstatus()
{
int local=status;
System.out.println("status ="+local);
local++;
try
{
System.out.println(Thread.currentThread().getName().toString());
Thread.sleep(50);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
status=local;
System.out.println("now status="+local);
return status;
}
}

Dept. Of MCA

RNSIT

Page 64

10MCA56

Software Design Laboratory

1RN11MCA01

Output:
status =0
Thread-1
now status=1
status =1
Thread-1
now status=2
status =2
Thread-1
now status=3
status =3
Thread-1
now status=4
status =4
Thread-1
now status=5
Thread-1has died
status =5
Thread-2
now status=6
Thread-2has died
the master will now die...

Dept. Of MCA

RNSIT

Page 65

You might also like