0% found this document useful (0 votes)
65 views52 pages

(Type The Document Title) : 1.expert

This document contains code examples demonstrating the Command design pattern. The code shows a text field component with buttons to perform bold, capitalize, and undo operations on the text. When a button is clicked, an action listener is called which changes the text field font or text depending on the button's command. The listener implements the Command interface to encapsulate the different text formatting operations as command objects.

Uploaded by

Komal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views52 pages

(Type The Document Title) : 1.expert

This document contains code examples demonstrating the Command design pattern. The code shows a text field component with buttons to perform bold, capitalize, and undo operations on the text. When a button is clicked, an action listener is called which changes the text field font or text depending on the button's command. The listener implements the Command interface to encapsulate the different text formatting operations as command objects.

Uploaded by

Komal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

[Type the document title]

1.Expert
a.Pattern Instance:

b.class diagram:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]
Sale.java:
import java.util.Set;

public class Sale


{
private double total;
public void getTotal()
{
ProductSpecification pd = new
ProductSpecification();
SalesLineItem s1 = new SalesLineItem();
total = pd.getPrice() * s1.getsubTotal();
System.out.println(" total sale is : " +total);

}
SalesLineItem.java:

public class SalesLineItem


{
private int qty = 100;
public double getsubTotal()
{
return qty;
}

ProductSpecification.java:

public class ProductSpecification

{
private double price = 43.89;
public double getPrice()
{
return price;
}
}
Register.java:

import java.util.Set;
public class Register
{
public static void main(String[] args)
{
Sale s = new Sale();
s.getTotal();
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]
OUTPUT:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

2.controller
a.Pattern Instance:

b.ClassDiagram:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

HomeView.java:

public class HomeView


{
public void show()
{
System.out.println(" Displaying Home Page ");
}
}

StudentView.java:

public class StudentView {


public void show()
{
System.out.println(" Displaying Home Page ");
}
}

Dispatcher.java:

public class Dispatcher


{
private StudentView studentView;
private HomeView homeView;
public Dispatcher()
{
studentView = new StudentView();
homeView=new HomeView();
}
public void dispatch(String request)
{
if(request.equalsIgnoreCase("STUDENT"))
{
studentView.show();
}
else
{
homeView.show();
}
}
}

FrontController.java:

public class FrontController


{
private Dispatcher dispatcher;
public FrontController()
{

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

dispatcher = new Dispatcher();


}
private boolean isAuthenticUser()
{
System.out.println(" User is Authenticated successfully ");
return true;
}
private void trackRequest(String request)
{
System.out.println(" PAge Requested : " +request);
}
public void dispatchRequest(String request)
{
trackRequest(request);
if(isAuthenticUser())
{
dispatcher.dispatch(request);
}
}
}

FrontControllerPAtternDemo.java:

public class FrontControllerPAtternDemo


{
public static void main(String[] args)
{
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

PAge Requested : HOME


User is Authenticated successfully
Displaying Home Page
PAge Requested : STUDENT
User is Authenticated successfully
Displaying Home Page

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

3.Publisher-Subscriber

Example: An embedded application; An interrupt-driven module keeps track of


temperature of the furnace. When the temperature is beyond preset upper /
lower limits, a module that controls the heating element must be informed.
Another module that displays an indicator also needs to know of such a change.
Further, a log module also needs this information.
a.Pattern Instance

b.Class diagram

c.Sequence Diagram

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

TemperatureController.java:

import java.util.Observable;
import java.util.Observer;
public class TemperatureController implements Observer
{
Observable observable;
private float temperature;
public TemperatureController(Observable observable)
{
this.observable = observable;
observable.addObserver(this);
}
public void update(Observable obs, Object arg)
{
if (obs instanceof TemperatureTracker)
{
TemperatureTracker temperatureTracker =(TemperatureTracker) obs;
this.temperature = temperatureTracker.getTemperature();
display();
}
}
public void display()
{
System.out.println(" TemperatureController : Current temp : "
+ temperature + " F Degrees");
}
}

TemperatureDisplay.java:

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
public class TemperatureDisplay implements Observer
{
List<Float> temps = new ArrayList<Float>();
private float temperature;
public TemperatureDisplay(Observable observable)
{
observable.addObserver(this);
}
public void update(Observable observable, Object arg)
{
if (observable instanceof TemperatureTracker)
{

TemperatureTracker TemperatureTracker = (TemperatureTracker)observable;

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

temperature = TemperatureTracker.getTemperature();
display();
}
}
public void display()
{
System.out.println(" Temperature Display : temperature list below or higher than
the cutoff");
for (int i = temps.size() - 1; i >= 0; i--)
{
System.out.println(temps.get(i) + "F Degrees ");
}
}
}

TemperatureTracker.java:

import java.util.*;
public class TemperatureTracker extends Observable
{
private float temperature;
private float upperThreshold = 80.0f;
private float lowerThreshold = 30.0f;
public TemperatureTracker()
{
}
public void measurementsChanged()
{
setChanged();
notifyObservers();
}
public void setMeasurements(float temp)
{
temperature = temp;
if (temperature < lowerThreshold)
{
measurementsChanged();
}
else if (temperature > upperThreshold)
{
measurementsChanged();
}
}
public float getTemperature()
{
return temperature;
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

TemperatureStation.java:

import java.util.Scanner;
public class TemperatureStation
{
public static void main(String[] args)
{
TemperatureTracker Tc = new TemperatureTracker();
TemperatureDisplay currentCondition = new TemperatureDisplay(Tc);
TemperatureController forecastDisplay = new TemperatureController(Tc);
Scanner sc = new Scanner(System.in);
for(int i=0;i<5;i++)
{
System.out.println("Enter temperature " );
float temp = sc.nextFloat();
Tc.setMeasurements(temp);
}
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

Enter Temprature:
15
TempratureController:current temp:15.0Fdegrees
TempratureDisplay:tempratures list below or higher than cutoff
15.0Fdegrees
Enter Temprature:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

4.Command:

a.Class Diagram:

Myevents.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Myevents implements ActionListener
{
JTextField jtf;
Font f;
Myevents(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 if(show.equals(show.toLowerCase()))
jtf.setText((jtf.getText()).toLowerCase());
else
jtf.setFont(f);

}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

DisplayText.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisplayText extends JFrame
{
JTextField jtf = new JTextField(10);
JLabel jlb = new JLabel("sentence");
DisplayText()
{
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 Myevents(jtf,f));
button2.addActionListener(new Myevents(jtf,f));
button3.addActionListener(new Myevents(jtf,f));
}
public static void main(String [] args)
{
DisplayText dt = new DisplayText();
dt.setSize(500,500);
dt.setVisible(true);
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

5.Forwarder-Receiver:
Example: A simple peer-to-peer message exchange scenario; Underlying
communication protocol is TCP/IP.

a.Pattern Instance

b.Class diagram

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

c.Sequence Diagram

Entry.java:

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

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

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


oStr = s.getOutputStream();
oStr.write(data);
oStr.flush();
oStr.close();
s.close();
}
catch(IOException e)
{
System.out.println("Forerror" +e);
}
}
Message.java:
public class Message
{
public String sender;
public String data;
public Message(String thesender, String rawData)
{
sender = thesender;
data = rawData;
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

Reciver.java:

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Reciver
{
private ServerSocket srvS;
private Registry reg;
private Socket s;
private InputStream iStr;
private String myName;
public Reciver(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();
}
}
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);

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

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

Registry.java:

import java.util.*;

public 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:

public class Server


{
Reciver r;
Forwarder f;
static Registry reg = new Registry();
public void execute()

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

{
Message result = null;
r = new Reciver("Server", reg);
f = new Forwarder("Server", reg);
Message msg = new Message("Server", " I am alive");
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();
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

6.Client-Dispatcher-Server

Example: A simplified implementation of RPC

a. Pattern Instance:

b.The Class Diagram :

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

CDS.java
public class CDS
{
public static Dispatcher disp = new Dispatcher();
public static void main(String[] args)
{
Service s1 = new PrintService("printSvc1","srv1");
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();
}
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();

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

}
catch(NotFound n)
{
System.out.println("Not Available");
}
}
}
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 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);
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

PrintService.java
public class PrintService extends Service
{
private Client client;
private Dispatcher dispatcher;
public PrintService(String svc,String srv)
{
super(svc,srv);
}
public void runService()
{
System.out.println("Service : " + nameofservice + " by " + nameofserver);
}
}

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


}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

Service : printSvc1 by srv1


Service : printSvc2 by srv2
Not Available

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

7. Proxy

Example: A highly simplified implementation of a proxy web server.

a.Pattern Instance :

b.Class Diagram :

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

c.Sequence Diagram

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("[email protected]","Hello","A test mail");
emailService.receiveMail("[email protected]");
} }

EMailService.java

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

public interface EMailService


{
public void sendMail(String receiver, String subject, String text);
public void receiveMail(String 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);
}
}
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 + ".");
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

Sending mail to [email protected] with subject' Hello' and message' A test mail'.
Receiving mail from [email protected].

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

8.Facade

a.Pattern Instance:

b.Class Diagram:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

Shape.java:

public interface Shape


{
public void draw();
}

Rectangle.java:

public class Rectangle implements Shape


{
public void draw()
{
System.out.println(" Rectangle ::draw()");
}
}

Square.java:

public class Square implements Shape


{
public void draw()
{
System.out.println(" Square ::draw()");
}
}

Circle.java:

public class Circle implements Shape


{
public void draw()
{
System.out.println(" Circle ::draw()");
}
}

ShapeMaker.java:

public class ShapeMaker


{
private Shape Circle;
private Shape Rectangle;
private Shape Square;

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

public ShapeMaker()
{
Circle=new Circle();
Rectangle = new Rectangle();
Square = new Square();

}
public void drawCircle()
{
Circle.draw();

}
public void drawRectangle()
{
Rectangle.draw();
}
public void drawSquare()
{
Square.draw();
}

}
FacedePatternDemo.java:

public class FacedePatternDemo


{
public static void main(String[] args)
{
ShapeMaker shapemaker = new ShapeMaker();
shapemaker.drawCircle();
shapemaker.drawRectangle();
shapemaker.drawSquare();
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

9. Polymorphism
a.Pattern Instance:

b.Class Diagram

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

Shape.java
public abstract class Shape
{
public abstract double area();
public abstract double perimeter();

}
Circle.java
public class Circle extends Shape
{
private final double radius;
final double pi=Math.PI;
public Circle()
{
this(1);
}
public Circle (double radius)
{
this.radius=radius;
}
@Override
public double area()
{
return pi*Math.pow(radius,2);

}
public double perimeter()
{
return 2*pi*radius;
}

Rectangle.java
public class Rectangle extends Shape
{
private final double width,length;
public Rectangle()
{
this(1,1);

}
public Rectangle(double width,double length)
{

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

this.width=width;
this.length=length;

}
@Override
public double area()
{
return width*length;
}
@Override
public double perimeter()
{
return 2*(width+length);
}

}
Triangle.java
public class Triangle extends Shape
{
private final double a,b,c;
public Triangle()
{
this(1,1,1);
}
public Triangle(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}
@Override
public double area()
{
double s=(a+b+c)/2;
return Math.sqrt(s*(s-a)*(s-b)*(s-c));
}
@Override
public double perimeter()
{
return a+b+c;

}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

TestShape.java
public class TestShape
{
public static void main(String [] args)
{
double width=5,length=7;
Shape rectangle=new Rectangle(width,length);
System.out.println("rectangle width:"+width+"and length:"+length+"\n
resulting area:"+rectangle.area()+"\n resulting perimeter:"+rectangle.perimeter()+"\n");
double radius=5;
Shape Circle=new Circle(radius);
System.out.println("Circle radius:"+radius+"\n resulting
area:"+Circle.area()+"\n resulting perimeter"+Circle.area()+"\n resulting
perimeter"+Circle.perimeter()+"\n");
double a=5,b=3,c=4;
Shape Triangle=new Triangle(a,b,c);
System.out.println("triangle sides length:"+a+","+b+","+c+"\n resulting area
:"+Triangle.area()+"\nResulting perimeter:"+Triangle.area()+"\n");
}
}

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

10.Whole-Part
Example: Implementation of any collection like a set.

a.Pattern instance:

b.Class diagram:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

Application.java:
import java.util.*;

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("Discount for FamilyPack is");

System.out.println(familyPack.getPrice());

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

List item2s = new ArrayList();

item2s.add(new ColdDrink("Pepsi", "cold drink", 10));

item2s.add(new ColdDrink("Coke", "cold drink", 20));

item2s.add(new ColdDrink("maza", "cold drink", 15));

item2s.add(new ColdDrink("Pepsi", "cold drink", 10));

item2s.add(new ColdDrink("Coke", "cold drink", 20));

item2s.add(new ColdDrink("maza", "cold drink", 15));

ColdDrinkPartyPack partyPack = new ColdDrinkPartyPack(item2s);

System.out.println("Discount for PartyPack is");

System.out.println(partyPack.getPrice());

ColdDrink.java:

public class ColdDrink implements Item

private String itemName;

private String iemDesc;

private double price;

public ColdDrink(String itemName, String desc, double price){

this.itemName=itemName;

this.iemDesc= desc;

this.price = price;

public double getPrice()

return price;

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

public String getItemName()

return itemName;

public String getIemDesc()

return iemDesc;

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

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

public ColdDrinkPartyPack(List items)

super.addAll(items);

public double getPrice(){

return super.getPrice() - super.getPrice()*.25; // get 25% discount on party pack

Composite.java

import java.util.*;

public abstract class Composite implements Item

List<Item> items = new ArrayList<Item>();

public void add(Item itm)

items.add(itm);

public void remove(Item itm)

items.remove(itm);

public void addAll(List lst)

items.addAll(lst);

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

public double getPrice()

double sum=0;

for (Item i: items)

sum += i.getPrice();

return sum;

Item.java

public interface Item

public double getPrice();

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT:

Discount for FamilyPack is


38.25
Discount for PartyPack is
67.5

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

11.Master-Slave
Example: A multithreaded implementation of any parallelized divide-and-
conquer algorithm

a.Pattern instance:

b.Class diagram:

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

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

for(int i=0;i<SlaveCount;i++)
{
slaves[i].start();
}
for(int i=0;i<SlaveCount;i++)
{
try
{

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

slaves[i].join();
}
catch(InterruptedException ie)
{
System.err.println(ie.getMessage());

}
finally
{
System.out.println(slaves[i].getName()+"has died");
}
}
System.out.println("The master will now die...");
}
}

Resource.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("nowStatus="+local);
return Status;
}
}

Slave.java
import com.ibm.oti.shared.Shared;

public class Slave extends Thread


{
private Resource sharedResource;

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

private boolean done=false;


public void halt()
{
done=true;
}
public Slave(Resource rcs)
{
sharedResource=rcs;
}
protected boolean task()
{
int Status=sharedResource.incStatus();
return (Status>=20);
}
public void run()
{
while(done!=true)
{
done=task();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
}
}
}

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

KLEDRMSSCET, Dept.ofMCA,Belagavi
[Type the document title]

OUTPUT

KLEDRMSSCET, Dept.ofMCA,Belagavi

You might also like