Beruflich Dokumente
Kultur Dokumente
V SEMESTER
LABORATORY MANUAL
Year 2015
Prepared By
Dr. Jasmine K S & Mrs. Savita SS
INDEX
SI.NO
Contents
PageNo
1.
03
2.
05
3.
15
4.
5.
6.
7.
8.
9.
10.
11.
Expert
Example: A Point Of Sale (POS) system is a computerized
application used (in part) to record sales and handle payments. It
includes hardware components such as a computer and bar code
scanner, and software to run the system. It interfaces to various
service applications, such as a third-party tax calculator and inventory
control. Furthermore, POS system will interact with different clients
with disparate needs in terms of business rule processing. Each client
will desire a unique set of logic to execute at certain predictable
points in scenarios of using the system, such as when a new sale is
initiated or when a new item is added. The POS will be calculating
the total sales at any given point of time.
Controller
Example: A Point Of Sale (POS) system.
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.
Command Processor
Example: A simple Text Editor; Facilities provided include making
the text bold, making the text in to all upper case; An Undo feature is
to be implemented.
Forwarder-Receiver
Example: A simple peer-to-peer message exchange scenario;
Underlying communication protocol is TCP/IP.
Client-Dispatcher-Server
Example: A simplified implementation of RPC
Proxy
Example: A highly simplified implementation of a proxy web server.
Faade
Example: Design a Home Theater System which consist of different
components like Projector, to project the movie on screen, DVD
Player to play the movie, Amplifier to control the sound effects. User
wants to control all the devices using single remote to start watching
18
23
29
38
45
52
60
66
12.
13.
14.
movie and close all the devices by one command using same remote
Polymorphism
Example: Drawing Shapes
Whole-Part
Example: Implementation of any collection like a set.
Master-Slave
Example: A multithreaded implementation of any parallelized divideand-conquer algorithm
73
79
88
15.
97
16.
99
17.
103
Lab Outcomes
1. Understand the fundamental principles of Object-Oriented analysis, design, development
and programming, in order to apply them in a real world problem
2. Demonstrate and represent the UML model elements, to enable visual representation of the system
being developed which meets the different views of stakeholders within realistic social, technical
and economic constraints
3. Analyze and differentiate the static and dynamic behaviour of the system for achieving the
intended functionalities of the system
4. Evaluate Various patterns in object oriented design, which satisfies the prescribed
requirements and complexity of real world projects and formulate new design solutions
DO ..
Come prepared to the Lab.
Submit the Record to the faculty in charge and sign in the Log Book on entering the Lab.
Follow the Lab exercise cycles as instructed by the Department. Violating the same will
result in deduction of marks.
Use the same login(if any) assigned to each student.
Put the chairs back to its position before leaving the Lab.
Backlog exercises to be executed after completing regular exercises.
DONT ..
Move around in the lab during the lab session.
Tamper System Files or Try to access the Server.
Write Data Sheets or Records in the Lab.
Change the system assigned without the notice of the Lab Staff.
Teaching friends/ Class mates during lab hours.
LAB CYCLES
CLASS DIAGRAM
A class diagram in the Unified Modeling Language (UML), is a type of static structure diagram
that describes the structure of a system by showing the system's classes, their attributes, and the
relationships between the classes.
CREATE A NEW CLASS DIAGRAM
SEQUENCE DIAGRAM
A Sequence Diagram describes a pattern of interaction among participants, arranged in a
chronological order. It shows the participants in the interaction and the messages they send. The
following shows some basic elements in a Sequence Diagram:
CREATE A NEW SEQUENCE DIAGRAM
10
11
ACTIVITY DIAGRAM
Activity Diagrams are a high-level flow chart that are particularly useful in representing
workflow. They represent a step-by-step model of a system, showing its processes or
transformations. The following shows the basic editor and elements of Activity Diagrams:
CREATE A NEW ACTIVITY DIAGRAM
12
13
Step1: A new project is created and the main page within model is selected
Step2: Select Pattern Explorer -->Behavioral , Creational, Structural patterns
Step2: View the Pattern Explorer
Step3: Select a pattern into the main workbench by drag & drop method
Step4: Create necessary classes, interfaces
Step5: Drag & Drop the created classes into main workbench from the project explorer
Step6: Add attributes, operations into the specific classes in the pattern
Step7: Generate the transformation configuration file (filename.tc)
Step8: Right Click on *.tc file in project explorer and select Transform---> UML to Java
Ste8: Execute the code after making necessary modifications
14
Class Diagram
15
Sequence Diagram
Activity Diagram
16
Participants:
InformationExpert: This is the class, which has the information to fulfill the responsibility. We assign the
responsibility to this class to accomplish the behavior.
Client: The class which will be using the InformationExpert class.
Context:
Use Expert pattern when there is a need to
Maintain encapsulation of information
low coupling
highly cohesive classes
Pattern Instance:
UseCase Diagram:
Class Diagram:
18
Sequence diagram:
Communication diagram:
19
Activity Diagram:
20
Implementation:
//ProductDescription.java
public class ProductDescription {
//
}
//Sale.java
public class Sale {
public SalesCounter Salecounter;
private float total;
public float gettotal()
{
ProductDescription pd=new ProductDescription();
SaleLineItem sli=new SaleLineItem();
total=(pd.getPrice()*sli.getsubTotal());
return total;
}
}
//SalesLineItem.java
public class SaleLineItem {
public SalesCounter SaleCounter;
21
}
//SalesController.java
public class SalesCounter {
//public Sale Sales;
//public SaleLineItem salelineitem;
//public ProductDescription productdiscription;
public static void main(String[] args)
{
float total;
Sale s=new Sale();
total=s.gettotal();
System.out.println("total sales is :"+total);
}
}
Output:
The Total Sale is 4389.00
Controller
Example: A Point Of Sale (POS) system
Intent:
An initial point of contact for handling processing of each user across multiple requests.
Participants:
Controller : The controller is the initial contact point for handling all requests in
the system. The controller may delegate to a helper to complete
authentication and authorization of a user or to initiate contact
retrieval.
Dispatcher: A dispatcher is responsible for view management and navigation, managing
the choice of the next view to present to the user, and providing the
mechanism
for
vectoring
control
to
this
resource.
A dispatcher can be encapsulated within a controller or can be a separate
component working in coordination. The dispatcher provides either a static
dispatching to the view or a more sophisticated dynamic dispatching
mechanism.
For example, The dispatcher uses the RequestDispatcher object (supported in
the servlet specification) and encapsulates some additional processing.
23
Context:
The
presentation-tier
request
handling
mechanism
must
coordinate processing of each user across multiple requests.
mechanisms may be managed in either a centralized or decentralized manner
control
and
Such control
Pattern Instance:
Class Diagram:
24
Sequence Diagram:
Communication Diagram:
25
Activity Diagram:
Implementation:
Sale.java
public class Sale {
26
ConcreteObservable - concrete Observable class. It maintain the state of the object and
when a change in the state occurs it notifies the attached Observers.
Observer - interface or abstract class defining the operations to be used to notify this
object.
ConcreteObserverA, ConcreteObserver2 - concrete Observer implementations.
Context
A component uses data or information provided by another component
Note:In Java, in the java.util package, there is an Observable class and an Observer interface that
permit a programmer to set up "observables" and "observers" that respond to changes in them.
Pattern Instance:
29
Class Diagram
Sequence Diagram
30
Communication Diagram
Activity Diagram
31
Implementation:
FurnaceStation.java
publicclassFurnaceStation
{
publicstaticvoid main(String []args)
{
FurnaceDatafd=newFurnaceData();
HeatingControlhc= newHeatingControl(fd);
IndicatorData id= newIndicatorData(fd);
LogDatald=newLogData(fd);
fd.setmeasurement(180f,30.4f);
fd.setmeasurement(80f,130.4f);
}
}
FurnaceData.java
import java.util.Observable;
public class FurnaceData extends Observable {
private Float Temprature;
public Float getTemprature()
32
{
return Temprature;
}
public void setTemprature(Float theTemprature)
{
Temprature = theTemprature;
}
private Float Pressure;
public Float getPressure()
{
return Pressure;
}
public void setPressure(Float thePressure)
{
Pressure = thePressure;
}
public void FurnaceData()
{
}
public void measurementchanged()
{
this.setChanged();
this.notifyObservers(); //call update method of each observer
}
public void setmeasurement(Float temp,Float hum,Float p)
{
this.Temprature=temp;
this.Pressure=p;
this.measurementchanged();
}
public void Notify()
{ }
}
HeatingControl.java
importjava.util.Observable;
importjava.util.Observer;
publicclassHeatingControl implements Observer
{ private Object Observable;
privatefloatTemperature;
privatefloatPressure;
publicHeatingControl(Observable observable)
{ this.Observable=observable;
observable.addObserver(this);
}
33
publicvoid Display()
{ System.out.println("\nHeatingControl Display");
System.out.println("Current Heating conditions:"+Temperature+"F Degrees and"+Pressure+"%
Pressure \n");
if (this.Temperature> 100)
System.out.println("Temperature Higher than 100- CutoffValue");
else
System.out.println("Temperature Lesser than 100- CutoffValue---->"+Temperature);
if (this.Pressure> 70)
System.out.println("Pressure Higher than 70- CutoffValue");
else
System.out.println("Pressure Lesser than 70- CutoffValue---->"+Pressure);
}
publicvoid update(Observable o, Object arg)
{ if (o instanceofFurnaceData)
{
FurnaceDatafurnacedata=(FurnaceData)o;
this.Temperature=furnacedata.getTemprature();
this.Pressure=furnacedata.getPressure();
Display();
}
}
}
IndicatorData.java
importjava.util.Observable;
importjava.util.Observer;
publicclassIndicatorDataimplements Observer
{ private Object Observable;
privatefloatTemperature;
privatefloatPressure;
publicIndicatorData(Observable observable)
{ this.Observable=observable;
observable.addObserver(this);
}
publicvoid Display()
{ System.out.println("\nIndicatorControl Display");
System.out.println("Current Indicator conditions:"+Temperature+"F Degrees and"+Pressure+"%
Pressure \n");
if (this.Temperature> 100)
{
float t= this.Temperature -100;
System.out.println("Temperature Difference is---->"+t);
}
34
else
{
}
if (this.Pressure> 70)
{
float p= this.Pressure -70;
System.out.println("Pressure Difference is---->"+p);
}
else
{
float p1= 70 - this.Pressure;
System.out.println("Pressure Difference is---->"+p1);
}
}
publicvoid update(Observable o, Object arg)
{ if (o instanceofFurnaceData)
{
FurnaceDatafurnacedata=(FurnaceData)o;
this.Temperature=furnacedata.getTemprature();
this.Pressure=furnacedata.getPressure();
Display();
}
}
}
LogData.java
importjava.util.Observable;
importjava.util.Observer;
publicclassLogDataimplements Observer
{ private Object Observable;
privatefloatTemperature;
privatefloatPressure;
publicLogData(Observable observable)
{ this.Observable=observable;
observable.addObserver(this);
}
publicvoid Display()
{ System.out.println("\n Log Display");
System.out.println("Current Log conditions:"+Temperature+"F Degrees and"+Pressure+"%
Pressure \n");
}
publicvoid update(Observable o, Object arg)
{ if (o instanceofFurnaceData)
{
35
FurnaceDatafurnacedata=(FurnaceData)o;
this.Temperature=furnacedata.getTemprature();
this.Pressure=furnacedata.getPressure();
Display();
}
}
}
OUTPUT:
Log Display
Current Log conditions:180.0F Degrees and30.4% Pressure
IndicatorControl Display
Current Indicator conditions:180.0F Degrees and30.4% Pressure
Temperature Difference is---->80.0
Pressure Difference is---->39.6
HeatingControl Display
Current Heating conditions:180.0F Degrees and30.4% Pressure
Temperature Higher than 100- CutoffValue
Pressure Lesser than 70- CutoffValue---->30.4
Log Display
Current Log conditions:80.0F Degrees and130.4% Pressure
IndicatorControl Display
Current Indicator conditions:80.0F Degrees and130.4% Pressure
Temperature Difference is---->20.0
Pressure Difference is---->60.399994
HeatingControl Display
Current Heating conditions:80.0F Degrees and130.4% Pressure
Temperature Lesser than 100- CutoffValue---->80.0
Pressure Higher than 70- CutoffValue
Context
Applications that need flexible and extensible user interfaces or applications those provide services
related to the execution of user functions, such as scheduling or undo.
Pattern Instance:
37
Class Diagram
Sequence Diagram
38
Communication Diagram
Activity Diagram
39
Implementation:
Person.java
publicclass Person
{
publicstaticvoid main(String args[])
{
InputDeviceid = newInputDevice();
Editor er = newEditor();
Bold bl = new Bold(er);
UpperCaseuc = newUpperCase(er);
Undo un = new Undo(er);
id.setCommand(bl);
id.setCommand(uc);
id.setCommand(un);
id.BoldClicked();
40
id.UpperCaseClicked();
id.UndoClicked();
}
}
Command.java
publicinterface Command
{
publicvoid execute();
}
Editor.java
publicclass Editor
{
publicvoid Bold() {
System.out.println("Text Command : Bold");
}
publicvoidUpperCase() {
System.out.println("Text Command : UpperCase");
}
publicvoid Undo() {
System.out.println("Text Command : Undo");
}
}
InputDevice.java
publicclassInputDevice {
private Command command;
Editor ed = newEditor();
public Command getCommand() {
returncommand;
}
publicvoidsetCommand(Command theCommand) {
}
publicvoidinvokeCommand() {
}
publicvoidBoldClicked() {
ed.Bold();
}
publicvoidUpperCaseClicked() {
41
ed.UpperCase();
}
publicvoidUndoClicked() {
ed.Undo();
}
}
Bold.java
publicclass Bold implements Command {
public Editor receiver;
public Editor getReceiver() {
returnreceiver;
}
publicvoidsetReceiver(Editor theReceiver) {
receiver = theReceiver;
}
public Bold(Editor receiver) {
this.receiver = receiver;
}
publicvoid execute() {
thrownewjava.lang.UnsupportedOperationException();
}
}
UpperCase.java
publicclassUpperCaseimplements Command {
public Editor receiver;
public Editor getReceiver() {
returnreceiver;
}
publicvoidsetReceiver(Editor theReceiver) {
receiver = theReceiver;
}
publicUpperCase (Editor receiver) {
this.receiver = receiver;
}
publicvoid execute() {
42
thrownewjava.lang.UnsupportedOperationException();
}
}
Undo.java
publicclass Undo implements Command {
public Editor receiver;
public Editor getReceiver() {
returnreceiver;
}
publicvoidsetReceiver(Editor theReceiver) {
receiver = theReceiver;
}
public Undo(Editor receiver) {
this.receiver = receiver;
}
publicvoid execute() {
thrownewjava.lang.UnsupportedOperationException();
}
}
OUTPUT:
Text Command : Bold
Text Command :UpperCase
Text Command : Undo
43
Participants:
Peer: Provides application services and communicates with other peers
Forwarder:
Provides general interface for sending messages.
Marshals and delivers messages to remote receivers
Maps names to physical addresses.
Receiver:
Provides general interface for receiving messages.
Receives and unmarshals messages from remote receivers
44
Class Diagram
Sequence Diagram
45
Communication Diagram
Activity Diagram
46
Implementation:
Forwarder.java
public class Forwarder
{
publicPeer peer;
publicPeer getPeer()
{ returnpeer; }
public void setPeer(Peer thePeer)
{ peer=thePeer; }
publicReceiver receiver;
publicReceiver getReceiver()
{ returnreceiver; }
public void setReceiver(Receiver theReceiver)
{ receiver= theReceiver; }
public void marshal() { }
public void deliver() { }
public void sendMsg(String msg,Peerdest,Peersrc)
{
Receiver rt=dest.getReceiver();
rt.receiveMsg(msg,src);
}
}
47
Receiver.java
public class Receiver
{
publicPeer peer;
publicPeer getPeer()
{ returnpeer; }
public void setPeer(Peer thePeer)
{ peer= thePeer; }
publicForwarder forwarder;
publicForwarder getForwarder()
{ returnforwarder; }
public void setForwarder(Forwarder theForwarder)
{ forwarder= theForwarder; }
public void receive() { }
public void unmarshal() { }
public void receiveMsg(String msg,Peersrc)
{
System.out.println("\n\nMsg received from peer:"+src);
System.out.println("Msg:"+msg);
}
public void IPCmsg() { }
}
Peer.java
public class Peer
{
publicString name;
publicPeer(String a)
{ name=a; }
publicReceiver receiver;
publicReceiver getReceiver()
{ returnreceiver; }
public void setReceiver(Receiver theReceiver)
{ receiver= theReceiver; }
publicForwarder forwarder;
publicForwarder getForwarder()
{ returnforwarder; }
public void setForwarder(Forwarder theForwarder)
{ forwarder= theForwarder; }
public void service(String msg,Peerdest)
{
System.out.println("sending msg to"+dest);
this.forwarder.sendMsg(msg,dest,this);
}
publicString toString()
{ return" "+name; }
}
mainclass.java
48
49
Context : A software system integrating a set of distributed servers, with the servers running locally or
distributed over a network.
50
Class Diagram
Sequence Diagram
51
Communication Diagram
Activity Diagram
52
Implementaion:
CDS.java
public class CDS extends PrintService
{
publicCDS(String srv, String svc)
{
super(srv, svc);
}
public static Dispatcher disp;
public static void main(String[] a)
{
disp=new Dispatcher();
53
if(v==null)
{
v=new Vector();
registry.put(svc,v);
}
v.addElement(obj);
}
publicService locateServer(String svc) {
Vector v=(Vector)registry.get(svc);
if(v==null || v.size()==0)
{
try{ throw new NotFound(); }
catch(NotFound e)
{
e.printStackTrace();
}
}
inti=(rnd.nextInt())%(v.size());
return(Service)v.elementAt(i);
}
}
Service.java
public abstract class Service {
privateString nameofservice;
privateObject nameofserver;
publicString getNameofservice() {
returnnameofservice;
}
publicObject getNameofserver() {
returnnameofserver;
}
publicService(String svc, String srv) {
nameofservice=svc;
nameofserver=srv;
CDS.disp.registerService(nameofservice, this);
}
public void runService() { }
}
PrintService.java
public class PrintServiceextends Service {
publicPrintService(String srv, String svc) {
super(srv,svc);
}
public void runService() {
System.out.println("Service : "+super.getNameofservice()+" ran by
"+getNameofserver());
}
55
}
OUTPUT:Service : printservice1 ran by server1
Service : printservice2 ran by server2
Pattern Instance:
56
Class Diagram
57
Activity Diagram
Sequence Diagram
58
Communication Diagram
59
Implementation:
CLASS 1:ApplicationClient.java
public class ApplicationClient {
public static void main(String[] args) {
Application application = new Application();
EmailServiceemailService =
application.locateEmailService();
emailService.sendMail("abc@gmail.com","Hello","A Text
Mail");
emailService.receiveMail("abc@gmail.com");}}
CLASS 2:Application.java
public class Application {
publicEmailServicelocateEmailService()
{
EmailServiceeS = new ProxyEmailService();
returneS;
}
}
CLASS 3:EmailService.java
public interface EmailService {
public void sendMail(String receive,Stringsubject,String text);
public void receiveMail(String receive);
}
CLASS 4:ProxyEmailService.java
public class ProxyEmailService implements EmailService {
privateRealEmailServiceemailService;
public void receiveMail(String receive)
{
if(emailService==null)
{
emailService=new RealEmailService();
emailService.receiveMail(receive);
}
public void sendMail(String receive, String subject, String text)
{
if(emailService==null)
{
emailService = new RealEmailService();
}
emailService.sendMail(receive,subject,text);
}
}
CLASS 5:60
RealEmailService.java
public class RealEmailService implements EmailService
{
public void sendMail(String receive,Stringsubject,String text)
{
System.out.println("Sending mail to '" + receive + "'" + "with Subject
'" + subject + "' " + " and message '" + text + "'");
}
public void receiveMail(String receive)
{
System.out.println("Receiving Mail from ' " + receive +"'");
}
}
OUTPUT:Sending mail to 'abc@gmail.com'with Subject 'Hello' and message 'A
Text Mail'
Receiving Mail from ' abc@gmail.com'
Facade
o knows which subsystem classes are responsible for a request.
o delegates client requests to appropriate subsystem objects.
Subsystem classes
o implement subsystem functionality.
o handle work assigned by the Facade object.
o have no knowledge of the facade and keep no reference to it
Context:
An application that needs to decouple the classes of the subsystem from its clients and other subsystems,
thereby promoting subsystem independence and portability by providing a simple interface.
61
Pattern Instance:
Class Diagram:
62
Sequence Diagram:
Communication Diagram:
63
Activity Diagram:
64
Implementation:
Code:
Amplifier.java
public class Amplifier {
String description;
DvdPlayer dvd;
public Amplifier(String description)
{ this.description = description; }
public void on()
{ System.out.println(description + " on"); }
public void off()
{ System.out.println(description + " off"); }
public String toString()
{ return description; }
}
DvdPlayer.java
public class DvdPlayer {
String description, movie;
Amplifier amplifier;
public DvdPlayer(String description, Amplifier amplifier) {
this.description = description;
this.amplifier = amplifier;
}
public void on()
{ System.out.println(description + " on"); }
public void off()
{ System.out.println(description + " off"); }
public void play(String movie)
{
this.movie = movie;
System.out.println(description + " playing \"" + movie + "\"");
}
public void stop()
{ System.out.println(description + " stopped \"" + movie + "\"");}
public String toString()
{ return description; }
}
Projector.java:
public class Projector {
String description;
DvdPlayer dvdPlayer;
public Projector(String description, DvdPlayer dvdPlayer) {
this.description = description;
this.dvdPlayer = dvdPlayer;
65
}
public void on()
{ System.out.println(description + " on"); }
public void off()
{ System.out.println(description + " off"); }
public void tvMode()
{ System.out.println(description + " in tv mode"); }
public String toString()
{ return description; }
}
HomeTheaterFacade.java
public class HomeTheaterFacade {
Amplifier amp;
DvdPlayer dvd;
Projector projector;
HomeTheaterFacade(Amplifier amp, DvdPlayer dvd, Projector prj)
{
this.amp = amp;
this.dvd = dvd;
this.projector = prj;
}
public void watchMovie(String movie) {
System.out.println("Get ready to watch a movie...");
projector.on();
amp.on();
dvd.on();
dvd.play(movie);
}
public void endMovie() {
System.out.println("Shutting movie theater down...");
projector.off();
amp.off();
dvd.stop();
dvd.off();
}
}
HomeTheaterTestDrive.java:
public class HomeTheaterTestDrive {
public static void main(String[] args) {
Amplifier amp = new Amplifier("Top-O-Line Amplifier");
DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp);
Projector projector = new Projector("Top-O-Line Projector", dvd);
HomeTheaterFacade homeTheater =
new HomeTheaterFacade(amp, dvd, projector);
homeTheater.watchMovie("Write your own movie name !!");
homeTheater.endMovie();
66
}}
Output:
Get ready to watch a movie...
Top-O-Line Projector on
Top-O-Line Amplifier on
Top-O-Line DVD Player on
Top-O-Line DVD Player playing "Write your own movie name !!"
Shutting movie theater down...
Top-O-Line Projector off
Top-O-Line Amplifier off
Top-O-Line DVD Player stopped "Write your own movie name !!"
Top-O-Line DVD Player off
Note: In Java, polymorphism is realized by overriding a method from a super class or implementing an
interface. The implemented overridden methods are polymorphic in that a client class uses the same
method, but the behaviour depends on the type of the object being referenced.
67
PATTERN INSTANCE
USECASE DIAGRAM
ACTIVITY DIAGRAM
68
CLASS DIAGRAM
SEQUENCE DIAGRAM
69
COMMUNICATION DIAGRAM
70
Implementation:
Ishape.java
publicinterfaceIshape {
publicvoid area();
publicvoid name();
}
Circle.java
publicclass Circle implementsIshape
{
private Double PI=3.14;
public Double getPI()
{
returnPI; }
publicvoidsetPI(Double thePI)
{
PI = thePI;
}
private Double radius;
public Double getRadius()
{
returnradius; }
publicvoidsetRadius(Double theRadius)
{
radius = theRadius; }
publicvoid area()
{
System.out.println("The radius you provided is:
"+radius);
double area=PI*radius*radius;
System.out.println("Area is "+area+" sq.units");
}
publicvoid name()
{
System.out.println("The name of this Shape is
Circle"); }
}
Triangle.java
publicclass Triangle implementsIshape
{
private Double base;
71
publicvoidsetBase(Double theBase)
{
base = theBase;
}
private Double height;
public Double getHeight()
{
returnheight; }
publicvoidsetHeight(Double theHeight)
{
height = theHeight; }
publicvoid area()
{
System.out.println("The base and height you provided
are "+base+" "+height+ " respectively");
doublearea=(base*height)/2;
System.out.println("Area is "+area+" sq.units");
}
publicvoid name()
{
System.out.println("The name of this Shape is
Triangle");
}
}
mainclass.java
publicclassmainclass
{
publicstaticvoid main(String[] args)
{
Circle c=newCircle();
Triangle t=newTriangle();
c.setRadius(5.0);
c.name();
c.area();
t.setBase(2.0);
t.setHeight(4.0);
t.name();
t.area();
}
}
72
OUTPUT
The name of this Shape is Circle
The radius you provided is: 5.0
Area is 78.5 sq.units
The name of this Shape is Triangle
The base and height you provided are 2.0 4.0 respectively
Area is 4.0 sq.units
LABCYCLE 12: (VTU List of Programs)
Whole-Part
Example: Implementation of any collection like a set.
Intent: The intent of this pattern is to compose objects into tree structures to represent partwhole hierarchies. Composite lets clients treat individual objects and compositions of objects
uniformly.
Participants:
Component - Component is the abstraction for leafs and composites. It defines the
interface that must be implemented by the objects in the composition. For example a file
system resource defines move, copy, rename, and getSize methods for files and folders.
Leaf - Leafs are objects that have no children. They implement services described by the
Component interface. For example a file object implements move, copy, rename, as well
as getSize methods which are related to the Component interface.
Composite - A Composite stores child components in addition to implementing methods
defined by the component interface. Composites implement methods defined in the
Component interface by delegating to child components. In addition composites provide
additional methods for adding, removing, as well as getting components.
Client - The client manipulates objects in the hierarchy using the component interface.
Context:
The composite pattern applies when there is a part-whole hierarchy of objects and a client needs
to deal with objects uniformly regardless of the fact that an object might be a leaf or a branch.
Pattern Instance:
73
Sequence Diagram
74
Communication Diagram
75
76
Activity Diagram:
Class Diagram:
77
Implementation:
CLASS 1:Application.java
importjava.util.*;
//collection (several colddrinks) as a whole (pack)
public class Application {
public Application() {
}
@SuppressWarnings("unchecked")
public static void main(String[] args){
List items =
newArrayList();
items.add(new ColdDrink("Pepsi","cold drink",10));
items.add(new ColdDrink("Coke","cold drink",20));
items.add(new ColdDrink("maza","cold drink",15));
ColdDrinkFamilyPackfamilyPack =
newColdDrinkFamilyPack(items);
System.out.println("Discount for FamilyPack is");
System.out.println(familyPack.getPrice());
List item2s =
newArrayList();
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));
ColdDrinkPartyPackpartyPack =
newColdDrinkPartyPack(item2s);
System.out.println("Discount for PartyPack is");
System.out.println(partyPack.getPrice());
}}
CLASS 2:ColdDrink.java
public class ColdDrink implements Item {
private String itemName;
private String iemDesc;
private double price;
publicColdDrink(String itemName, String desc, double price){
this.itemName=itemName;
this.iemDesc= desc;
this.price = price;
}
public double getPrice() {
return price;
78
}
/*public void setItemName(String itemName) {
this.itemName = itemName;
}*/
public String getItemName() {
returnitemName;
}
/*public void setIemDesc(String iemDesc) {
this.iemDesc = iemDesc;
}*/
public String getIemDesc() {
returniemDesc;
}
}
CLASS 3:ColdDrinkFamilyPack.java
importjava.util.List;
public class ColdDrinkFamilyPack extends Composite{
publicColdDrinkFamilyPack(List items){
super.addAll(items);
}
public double getPrice(){
returnsuper.getPrice() - super.getPrice()*.15; // get 15%
discount on family pack
}
}
CLASS 4:ColdDrinkPartyPack.java
importjava.util.List;
public class ColdDrinkPartyPack extends Composite {
publicColdDrinkPartyPack(List items){
super.addAll(items);
}
public double getPrice(){
returnsuper.getPrice() - super.getPrice()*.25; // get 25%
discount on family pack
}
}
CLASS 5:Composite.java
importjava.util.*;
public abstract class Composite implements Item {
/**
* @associates <{demp.composite.Item}>
*/
List<Item> items = new ArrayList<Item>();
public void add(Item itm) {
79
items.add(itm);
}
public void remove(Item itm) {
items.remove(itm);
}
public void addAll(List lst) {
items.addAll(lst);
}
public double getPrice() {
double sum=0;
for (Item i: items) {
sum += i.getPrice();
}
return sum;
}
}
CLASS 6:Item.java
public interface Item {
public double getPrice();
}
OUTPUT :Discount for FamilyPack is
38.25
Discount for PartyPack is
67.5
Pattern Instance:
Class Diagram
81
Sequence Diagram
Communication Diagram
82
Activity Diagram
83
Implementation:
CLASS 1:TestMaster.java
public class TestMaster {
public static void main(String[] args) {
Master master = new Master();
master.run();
}
}
CLASS 2:Master.java
public class Master {
privateintslaveCount = 2;
private Resource res = new Resource();
private Slave[] slaves = new Slave[slaveCount];
public void run() {
// create slaves:
for(int i = 0; i <slaveCount; i++) {
slaves[i] = new Slave(res);
}
// start slaves:
for(int i = 0; i <slaveCount; i++) {
slaves[i].start();
}
// wait for slaves to die:
for(int i = 0; i <slaveCount; i++) {
try {
//is used to wait for a thread to finish and terminate
slaves[i].join();
} catch(InterruptedExceptionie) {
System.err.println(ie.getMessage());
} finally {
System.out.println(slaves[i].getName() + " has died");
}
}
System.out.println("The master will now die ... ");
}
}
CLASS 3:Slave.java
class Slave extends Thread {
private Resource sharedResource;
privateboolean done = false;
public void halt() {
84
done = true;
}
//constructor
public Slave(Resource rcs) {
sharedResource = rcs;
}
protectedboolean task() {
// access sharedResource here
// for example:
int status = sharedResource.incStatus();
return (status >= 20);
// 20 <= status;
}
@Override
public void run() {
while (done != true) {
done = task();
// be cooperative:
try {
Thread.sleep(500);
} // sleep for 1 sec.
catch (Exception e) {
}
}
}
}
CLASS 4:Resource.java
public class Resource {
privateint status = 0;
public synchronized intincStatus() {
int local = status;
System.out.println("status = " + local);
local++;
try {
Thread.sleep(50);
} catch(Exception e) {
}
status = local;
System.out.println("now status = " + local);
return status;
}
}
OUTPUT:status = 0
now status = 1
status = 1
85
now status = 2
status = 2
now status = 3
status = 3
now status = 4
status = 4
now status = 5
status = 5
now status = 6
status = 6
now status = 7
status = 7
now status = 8
status = 8
now status = 9
status = 9
now status = 10
status = 10
now status = 11
status = 11
now status = 12
status = 12
now status = 13
status = 13
now status = 14
status = 14
now status = 15
status = 15
now status = 16
status = 16
now status = 17
status = 17
now status = 18
status = 18
now status = 19
status = 19
now status = 20
status = 20
now status = 21
Thread-0 has died
Thread-1 has died
The master will now die ...
86
SI.NO
1.
2. .
3.
4. .
5. .
Contents
Publisher-Subscriber:
Example : Weather Station Information
The weather Station will be broadcasting the current weather conditionslike
temperature, humidity and biometric pressure. Create an applicationwhich
receives the weather conditions and displays them in differentforms. (i.e.
displaying the current weather conditions, displaying weatherstatistics). All
displays will be updating the weather conditions inreal time, as and when the
new conditions are recorded.It is assumed that the weather conditions are
measured and that the devices are measuring the conditions and are stored in a
class.
Command Processor
Example : Multi-level undo
If all user actions in a program are implemented as command objects, the
program can keep a stack of the most recently executed commands. When the
user wants to undo a command, the program simply pops the most recent
command object and executes its undo() method.
Forwarder-Receiver
Example: Multimedia-based Chat Application
The chat application is related to the class Peer. Both have in common that
they constitute the core chat system controlled by a user, who can call specific
services, such as SendTextMessage. They are related via an inheritance
relation. The role of the classForwarder, implements its operations by
distribute-TextMessage. The Receiveris expressed by an inheritance relation
and it operates by pickUpTextMessages.
Client-Dispatcher-Server
Example: ShadowCopy Service
A graphical front end for the Shadow Copy service that lets users choose from
multiple versions of a file. The shadow copy service creates multiple copies of
a file as they are changed over time, so that users can revert to previous
versions.
Proxy
Example: Client Side Proxy:
A cache proxy is a client-side proxy that searches a local cache containing
recently received results. If the search is successful, the result is returned to the
client without the need of establishing a connection to a remote server.
Otherwise, the client request is delegated to the server or another proxy. For
example, most web browsers transparently submit requests for web pages to a
cache proxy, which attempts to fetch the page from a local cache of recently
downloaded web pages.
87
6. .
7.
Whole-Part
Example: A Hierarchical file System
an object-oriented and extensible programming model for the application
writers using
the application programming interface of an hierarchical file system.
Master-Slave
Example: voltage Data
Write an application that measures and logs a slowly changing voltage once
every five seconds. It acquires a waveform from a transmission line and
displays it on a graph every 100ms, and also provides a user interface that
allows the user to change parameters for each acquisition.In this application,
the master loop will contain the user interface. The voltage acquisition and
logging will happen in one slave loop, while the transmission line acquisition
and graphing will happen in another.
88
92
Lab Cycle 9:
Proxy
Data Sheet
Name of the Pattern
Record Writing:
Left-hand side
Right-hand side
Case Study
Pattern instance
Pattern Instance
UML Diagrams
UML Diagrams
Java Code
Implementation Code
Program Output
: 2 Marks
: 5 Marks
: 3 Marks
94
Instructions to students:
: 50 Marks
External Evaluation
: 50 Marks
Record Marks
: 20
Write Up
: 15%
: 30
Execution
: 70%
Viva Voce
: 15%
95