Upload
shashank-athreyasa-l
View
59
Download
1
Tags:
Embed Size (px)
DESCRIPTION
SD MANUAL
Citation preview
MASTER OF COMPUTER APPLICATIONS
V SEMESTER
SOFTWARE DESIGN LABORATORY (10MCA56)
LABORATORY MANUAL- REVISED VERSION
Year 2014
Prepared By
1. Dr. Jasmine K S 2. Mrs.Sandhya S
2
INDEX
SI.NO Contents PageNo
1. Software Design Lab Outcomes 03
2. Tool Exploration- Introduction to RSA 04
3. Practice Lab – Polymorphism Example – Drawing Shapes 14
4.
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.
20
5.
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.
28
6. Forwarder-Receiver
Example: A simple peer-to-peer message exchange scenario;
Underlying communication protocol is TCP/IP.
35
7. Client-Dispatcher-Server
Example: A simplified implementation of RPC 41
8. Proxy
Example: A highly simplified implementation of a proxy web server. 47
9. Whole-Part
Example: Implementation of any collection like a set. 54
10. Master-Slave
Example: A multithreaded implementation of any parallelized divide-
and-conquer algorithm
61
11. Extra Lab Programs 71
12. ViVa Voce Questions 73
13. Instruction for Conduction of Laboratory 77
3
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 differentiatethe static and dynamicbehavior of the system for achieving
the intended functionalities of the system
4. Implement the common patterns in object oriented design, which satisfies the
prescribed requirements and complexity of real world projects
4
Do’s and Don’t in the Laboratory
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.
DON’T …..
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.
5
LAB CYCLES
LabCycle 1: Tool Exploration- Introduction to RSA
Object-Oriented Modeling, or OOM, is a modeling paradigm mainly used in computer
programming. Prior to the rise of OOM, the dominant paradigm was procedural programming,
which emphasized the use of discreet reusable code blocks that could stand on their own, take
variables, perform a function on them, and return values.
The Object-Oriented paradigm assists the programmer to address the complexity of a problem
domain by considering the problem not as a set of functions that can be performed but primarily
as a set of related, interacting Objects. The modeling task then is specifying, for a specific
context, those Objects (or the Class the Objects belongs to), their respective set of Properties and
Methods, shared by all Objects members of the Class. The description of these Objects is a
Schema.
Object-oriented analysis and design (OOAD) is a software engineering approach that models a
system as a group of interacting objects. Each object represents some entity of interest in the
system being modeled, and is characterized by its class, its state (data elements), and its
behavior. Various models can be created to show the static structure, dynamic behavior, and run-
time deployment of these collaborating objects. There are a number of different notations for
representing these models, such as the Unified Modeling Language (UML).
Object-oriented analysis (OOA) applies object-modeling techniques to analyze the functional
requirements for a system. Object-oriented design (OOD) elaborates the analysis models to
produce implementation specifications. OOA focuses on what the system does, OOD on how the
system does it.
IBM Rational Software Architect, (RSA) made by IBM's Rational Software division, is a
comprehensive modeling and development environment that leverages the Unified Modeling
Language (UML) for designing architecture for C++ and Java 2 Enterprise Edition (J2EE)
applications and web services. Rational Software Architect is built on the Eclipse open-source
software framework and includes capabilities focused on architectural code analysis, C++, and
model-driven development (MDD) with the UML for creating resilient applications and web
services.
The benefits of using Rational Software Architect include:
Build software architecture that supports change with a common platform that facilitates easy
roundtrip engineering and synchronization of models and code.
Accelerate implementation of a successful service-oriented architecture (SOA) solution with
powerful tools and process guidance that empowers you to quickly build and maintain web
services
6
Leverage UML to ensure the numerous stakeholders of within your software development
projects are continuously communicating, and use defined specifications to jumpstart
development.
Create a New UML Project
To create a new UML project and an accompanying blank model, perform the following steps:
Step 1: On the File menu, click New Project to open the New Project Dialog.
Step 2: Expand the Modeling folder, then select UML Project. Click Next.
Step 3: Name the Project “Sample UML Project_ bankscenerio” and click Next.
Step 4: Type “Bank” in the File Name field and select Blank Model template.
Step 5: Click Finish to create the project and model.
Step6: Expand the diagrams icon and Bank icon in the Project Explorer view.
Fig1. Step1: Creating a New Project
7
Step2: Creating a Blank Model within the Project
Step3: Project Explorer Displays the Newly Created Project
8
USE CASE DIAGRAMS:
Use-Case diagrams are used to identify the required usages of a system in terms of actors and
use-cases. They are used to model a system's desired functions and its environment.
CREATE A NEW USECASE DIAGRAM
Fig: Sample Use Case Diagram
9
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
Fig: Sample Class Diagram
10
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
Fig: Sample Sequence Diagram
11
COLLABORATION (COMMUNICATION) DIAGRAM
A Communication Diagram describes a pattern of interaction among roles in collaboration. It
shows their participation in the interaction by their links to each other, and by the messages that
they send to each other.
CREATE A NEW COLLABORATION (COMMUNICATION) DIAGRAM
Fig:Sample Collaboration Diagram
12
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
Fig:Sample Activity Diagram
13
STATE CHART DIAGRAM
A State Machine Diagram represents the interaction and behavior of various elements using
states. A state represents a set of conditions that these elements hold. The machine then changes
state (or transitions) based on certain triggering events. The following shows the basic editor and
elements of State Machine Diagrams.
CREATE A NEW STATE CHART DIAGRAM
Fig: Sample State Chart Diagram
14
INTRODUCTION TO PATTERNS USING RSA - Selecting a pattern from a Pattern explorer
Window, Generating the transformation configuration file from a Class diagram andconverting into java
code
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
15
LABCYCLE 2: Practice Lab
POLYMORPHISM PATTERN
Develop an application for drawing various shapes ( Circle and Triangle) using the
concept of polymorphism
PATTERN INSTANCE
16
USECASE DIAGRAM
ACTIVITY DIAGRAM
CLASS DIAGRAM
17
SEQUENCE DIAGRAM
COMMUNICATION DIAGRAM
18
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; }
19
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;
public Double getBase()
{ returnbase; }
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;
20
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();
}
}
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
21
LABCYCLE 3: (VTU List of Programs)
Publisher-Subscriber
Intent: Defines a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically.
Participants:
Observable - interface or abstract class defining the operations for attaching and de-
attaching observers to the client. In the GOF book this class/interface is known as
Subject.
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.
Applicability
The change of a state in one object must be reflected in another object without keeping the
objects tight coupled. The framework we are writing needs to be enhanced in future with new
observers with minimal changes.
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:
Use Case Diagram
22
Class Diagram
23
Sequence Diagram
Communication Diagram
24
Activity Diagram
25
State Machine Diagram
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);
}
}
HeatingControl.java
importjava.util.Observable;
importjava.util.Observer;
publicclassHeatingControlimplements Observer
{ private Object Observable;
26
privatefloatTemperature;
privatefloatPressure;
publicHeatingControl(Observable observable)
{ this.Observable=observable;
observable.addObserver(this);
}
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");
27
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);
}
else
{ float t1= 100 - this.Temperature;
System.out.println("Temperature Difference is---->"+t1);
}
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");
28
System.out.println("Current Log conditions:"+Temperature+"F Degrees and"+Pressure+"%
Pressure \n");
}
publicvoid update(Observable o, Object arg)
{ if (o instanceofFurnaceData)
{
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
29
LABCYCLE 4: (VTU List of Programs)
Command Processor
Intent:Encapsulate a request in an object and allows the parameterization of clients with
different requests, saving the requests in a queue.
Participants:
Command - declares an interface for executing an operation;
ConcreteCommand - extends the Command interface, implementing the Execute method
by invoking the corresponding operations on Receiver. It defines a link between the
Receiver and the action.
Client - creates a ConcreteCommand object and sets its receiver;
Invoker - asks the command to carry out the request;
Receiver - knows how to perform the operations;
Applicability
- parameterizes objects depending on the action they must perform
- specifies or adds in a queue and executes requests at different moments in time
- offers support for undoable actions (the Execute method can memorize the state and allow
going back to that state)
- structures the system in high level operations that based on primitive operations
- decouples the object that invokes the action from the object that performs the action. Due to
this usage it is also known as Producer - Consumer design pattern.
Pattern Instance:
Use Case Diagram
30
Class Diagram
Sequence Diagram
31
Communication Diagram
Activity Diagram
32
State Machine Diagram
33
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();
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() {
34
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() {
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;
}
35
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() {
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();
}
36
}
OUTPUT:
Text Command : Bold
Text Command :UpperCase
Text Command : Undo
LABCYCLE 5: (VTU List of Programs)
Forwarder-Receiver
Intent: The Forwarder-Receiver design pattern provides transparent inter-process
communication for software systems with a peer-to-peer interaction model. It introduces
forwarders and receivers to decouple peers from the underlying communication mechanism.
Distributed peers collaborate to solve a particular problem. A peer may act as a client, requesting
services, as a server, providing services, or both. The details of the underlying inter-process
communication mechanism for sending or receiving messages (such as TCP/IP, sockets or
message queues) are hidden from the peers by encapsulating all system-specific functionality
into separate components. Examples of such functionality are the mapping of names to physical
locations, the establishment of communication channels, or the marshaling and unmarshaling of
messages.
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
Applicability:
Distributed applications that should allow the exchangeability of inter-process
communication mechanisms (TCP/IP, sockets)
Cooperation of components follows a peer-to-peer model
Communication between peers should not have a major impact on performance
37
Use Case Diagram
Class Diagram
Sequence Diagram
38
Communication Diagram
39
Activity Diagram
40
State Machine Diagram
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)
Page 16 of 38
{ receiver= theReceiver; }
public void marshal() { }
public void deliver() { }
public void sendMsg(String msg,Peerdest,Peersrc)
{
41
Receiver rt=dest.getReceiver();
rt.receiveMsg(msg,src);
}
}
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() { }
}
Page 17 of 38
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);
42
}
publicString toString()
{ return" "+name; }
}
mainclass.java
public class mainclass {
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);
Page 18 of 38
Peer p2=new Peer("peer2");
p2.setForwarder(f2);
p2.setReceiver(r2);
p1.service("hi.. Welcome to RVMCA 5th SEM SD LAB",p2);
p2.service("hi.. messege receive",p1);
}
}
OUTPUT
sendingmsg to peer2
Msg received from peer: peer1
Msg: hi.. Welcome to TOCE MCA 5th SEM SD LAB
Msg received from peer: peer2
Msg: hi..messege received
LABCYCLE 6: (VTU List of Programs)
Client-Dispatcher-Server
Example: A simplified implementation of RPC
Intent: A dispatcher component is an intermediary between clients and servers. The dispatcher
provides location transparency with a name service and hides details of the communication
connection.
Participants:
Forwarder-Receiver can be combined with this pattern to hide details of interprocess
communication.
Acceptor and Connector decouple connection set-up from connection processing.
Applicability:
A software system integrating a set of distributed servers, with the servers running locally or
distributed over a network
43
Use Case Diagram
Class Diagram
44
Sequence Diagram
Communication Diagram
45
Activity Diagram
46
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();
Client c1=new Client();
Service svc = new PrintService("printservice1","server1");
Service svc1=new PrintService("printservice2","server2");
c1.doTask();
}
}
Client.java
public class Client {
publicDispatcher dispatcher;
publicPrintServiceprintService;
public void setPrintService(PrintServicethePrintService)
{
printService = thePrintService;
}
public void doTask()
47
{
Service s;
try
{
s=CDS.disp.locateServer("printservice1");
s.runService();
}
catch(Exception e) { System.out.println(e.getMessage()); }
try
{
s=CDS.disp.locateServer("printservice2");
s.runService();
}
catch(Exception e) { System.out.println("Not Found "); }
}
}
Dispatcher.java
importjava.util.Hashtable;
Page 22 of 38
importjava.util.Random;
importjava.util.Vector;
classNotFoundextends Exception
{
private static final long serialVersionUID = 1L;
}
public class Dispatcher
{
publicClient client;
publicHashtableregistry=new Hashtable();
privateRandom rnd=new Random(123456);
public void registerService(String svc,Serviceobj)
{
Vector v=(Vector) registry.get(svc);
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)
{
48
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() { }
Page 23 of 38
}
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());
}
}
OUTPUT:-
Service : printservice1 ran by server1
Service : printservice2 ran by server2
LABCYCLE 7: (VTU List of Programs)
Proxy
Example: A highly simplified implementation of a proxy web server.
Intent:
49
Provide a surrogate or placeholder for another object to control access to it. Use an extra level of
indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation
to protect the real component from undue complexity.
Participants:
Subject - Interface implemented by the RealSubject and representing its services. The interface
must be implemented by the proxy as well so that the proxy can be used in any location where
the RealSubject can be used.
Proxy - Maintains a reference that allows the Proxy to access the RealSubject.
Implements the same interface implemented by the RealSubject so that the Proxy can be
substituted for the RealSubject. Controls access to the RealSubject and may be responsible for its
creation and deletion.
Other responsibilities depend on the kind of proxy.
RealSubject - the real object that the proxy represents.
Applicability:
The Proxy design pattern is applicable when there is a need to control access to an Object, as
well as when there is a need for a sophisticated reference to an Object.
Pattern Instance:
50
CLASS DIAGRAM:
51
Communication Diagram
52
State Machine Diagram
53
Implementation:
CLASS 1:-
ApplicationClient.java
public class ApplicationClient {
public static void main(String[] args) {
Application application = new Application();
EmailServiceemailService =
application.locateEmailService();
emailService.sendMail("[email protected]","Hello","A Text
Mail");
emailService.receiveMail("[email protected]");}}
CLASS 2:-
Application.java
public class Application {
publicEmailServicelocateEmailService()
{
EmailServiceeS = new ProxyEmailService();
returneS;
}
}
54
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:-
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 '[email protected]'with Subject 'Hello' and message 'A
Text Mail'
Receiving Mail from ' [email protected]'
55
LABCYCLE 8: (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 part-
whole 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.
Applicability:
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:
Usecase Diagram:
56
Sequence Diagram
Communication Diagram
57
58
State Machine Diagram
Activity Diagram:
59
Class Diagram:
60
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;
}
61
/*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) {
items.add(itm);
62
}
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
LABCYCLE 9: (VTU List of Programs)
Master-Slave
Example: A multithreaded implementation of any parallelized divide-and-conquer algorithm
Intent:
Handles computation of replicated services in a system to achieve fault tolerance and robustness.
Independent components providing the same services (slaves) are separated from the
component (master) responsible for invoking the services.
Participants:
Master:
Partitions work among several slave components
Starts the execution of the slave
Computes the results from sub-results of the slaves return
Slave:
Implements the subservice used by the master
63
Applicability:
Partitioning work into semantically identical subtasks
Pattern Instance:
Use Case Diagram
Class Diagram
64
Sequence Diagram
65
Communication Diagram
66
Activity Diagram
67
State Machine Diagram
68
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];
69
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() {
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();
70
// 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
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
71
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 ...
72
Extra Lab Programs
SI.NO Contents
1.
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.
2. .
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.
3.
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.
4. .
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.
5. .
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
73
downloaded web pages.
6. .
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.
7.
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.
74
Viva Voce Questions with Answers
1. Define Object Oriented Analysis? Object Oriented Analysis (OOA) is a method of analysis that examines
requirements from the perspective of the classes and objects found in the
vocabulary of the problem domain.
2. What is meant by Object Orientation? Object Oriented means we organize the software as a collection of discrete
objects that incorporate both data structure and behavior.
3. Write the characteristics of an object. Identity, classification, polymorphism, and inheritance.
4. What is a class? A class is a set of objects that share a common structure and a common
behavior.
5. Name two types of object diagram. Class diagram and instance diagram.
6. What is an attribute? Give example. An attribute is a data value held by the objects in a class .Example: name,
age and weight are attributes of Person class.
7. What is multiple inheritance? When one class inherits its state (attributes) and behavior from more than
one super class, it is referred to as multiple inheritances.
8. What is dynamic binding? The process of determining (dynamically) at run time which functions to
invoke is termed dynamic binding.
9. What is static binding? The process of determining at compile time which functions to invoke is
termed static binding.
10. What is object persistence? Objects have life time. They are created and can exist for a period of time. A file or a database
can provide support for objects having a longer life timelonger than the duration of the process
for which they were created. This characteristic is called object persistence.
11. What is polymorphism? Give an example. Polymorphism means that the same operation may behave differently on different classes. Ex.
Move operation. (Behave differently on the window class and chess Piece class).
12. What is cardinality? Cardinality specifies how many instances of one class may relate to a single instance of an
associated class.
13. What is a formal class or abstract class? Formal or abstract classes have no instances but define the common behaviors that can be
inherited by more specific classes.
14. What is a meta-class? A meta-class is a class about a class. They are normally used to provide instance variables and
operations.
15. Define Encapsulation?
75
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute
its structure and behavior.
16. What is the need of an Object diagram? An object diagram is used to show the existence of objects and their relationships in the logical
design of a system.
17. Write some applications of object model? They include Air traffic control, Animation, Avionics, Database, Robotics
etc.
18. What is meant by OMT functional model. OMT functional model uses dataflow diagram that shows the flow of data between different
processes in a business .Data flow diagrams use four primary symbols. They are process, data
flow, data store, external entity.
19. Names the diagrams of Booch Methodology. Class diagram, object diagram, state transition diagram, module diagram,
process diagram, interaction diagram.
20. Name the models in objectory. Use case model, domain object model, analysis object model,
implementation model, test model.
21. What is unified modeling language?
Unified modeling language is a language for specifying, conducting, visualizing and
documenting the software system and its components.
22. Write any two advantages of modeling? The main reason for modeling is the reduction of complexity. The cost of the modeling analysis
is much lower than the cost of similar experimentation conducted with real time.
23. Define Static model? It can be viewed as a snapshot of a system’s parameters at rest or a
specific point in time. They are needed to represent the structural or static aspect
of a system.
24. Define Dynamic model? It can be viewed as a collection of procedures or behaviors that taken
together reflect the behavior of a system over time. Dynamic modeling is the most
useful during the design and implementation phases of the system development.
25. What is an association? Give one example. An association is the relationship between the classes.
Ex person and company are the classes, works-for is the association name.
26. What is a qualifier? Give one example. A qualifier is an association attribute. The qualifier rectangle is part of the association path, not
part of the class.
27. What is a method? A method is the implementation of an operation for a class.
28. What is a use case? Use cases are scenarios for understanding system requirements. A use case is an interaction
between users and a system.
29. Name the three types of relationships in a use case diagram. Communication, Uses, extends.
30. Write the two types of Implementation diagram? Component diagram, deployment diagram.
76
31. What is an activity? An activity is a set of operations that is executing during the entire period an object is in a state.
32. Name the types of relationships among the objects. Association, super-sub structure, aggregation.
33. Write the guidelines for identifying the associations A dependency between two or more classes may be association A reference from one class to
another is an association.
34. Define pattern mining? The process of looking for patterns to document is called pattern mining
Some times called reverse architecture.
35. Define anti-patterns? An anti-pattern represents a worst practice while a pattern represents a best Practice. Anti-
patterns come in two varieties. Those describing a bad solution to a problem that resulted in a
bad situation and Those describing how to get out of a bad situation.
36. Define patterns template? Every pattern must be expressed in the form of a rule which is called as a Template. It should
establish a relationship between a context, a system of forces which arises in the context, and a
configuration.
37. Write the syntax for presenting the attribute that was suggested by UML. visibility name : type_expression = initial _value
Where visibility is one of the following
+ public visibility
# protected visibility
- private visibility
type_expression - type of an attribute
Initial_value is a language dependent expression for the initial value of a newly
created object.
38. Write the syntax for presenting the operation that was suggested by UML
visibility name : (parameter_list): return _type_expression Where visibility is one of the following
+ public visibility
# protected visibility
- private visibility
parameter- is a list of parameters.
Return_type_expression: is a language _dependent specification of the Implementation of the
value returned by the method.
75. What is a Façade? Facade classes are the public classes in a package for public behavior.
39. What is database model? Database model is a collection of logical constructs used to represent the data structure and data
relationships within the database.
40. What is the need of an Interaction diagram? An Interaction diagram is used to trace the exception of a scenario in the same context of an
object diagram.
41. What is the need of a Class diagram? A class diagram is used to show the existence of classes and their relationships in the logical
view of a system.
77
42. What is Behavior of an object? Behavior is how an object acts and reacts in terms of its state changes and message passing.
43. What are the characteristic features of an Interaction diagram? They include the representation of objects with its name and class
name. Each object has a life line. The order of messaging between objects is well defined.
44. Define forward engineering and revere engineering. Forward engineering means creating a relational schema from an existing object model
Reverse engineering means creating an object model from an existing relational database layout
(schema).
45.Briefly explain about the characteristics of an object and software
development processes? Characteristics of an object- Identity, classification, polymorphism,
inheritance.
software development processes- analysis, design, implementation, testing
Questions on Design Patterns
1. Mention some applications of observer pattern
2. Explain the command pattern
3. What are the participants in the command pattern?
4. Explain the dynamics of the command pattern
5. Mention some applications of command pattern
6. Explain the Forwarder Receiver pattern
7. What are the participants in the Forwarder Receiver pattern?
8. Explain the dynamics of the Forwarder Receiver pattern
9. Mention some applications of Forwarder Receiver pattern
10. Explain the Client Dispatcher Server pattern
11. What are the participants in the Client Dispatcher Server pattern?
12. Explain the dynamics of the Client Dispatcher Server pattern
13. Mention some applications of Client Dispatcher Server pattern
14. Explain the proxy pattern
15. What are the participants in the proxy pattern?
16. Explain the dynamics of the proxy pattern
17. Mention some applications of proxy pattern
18. Explain the Whole Part pattern
19. What are the participants in the Whole Part pattern?
20. Explain the dynamics of the Whole Part pattern
21. Mention some applications of Whole Part pattern
22. Explain the Whole Part pattern
23. What are the participants in the Whole Part pattern?
24. Mention some applications of Whole Part pattern
25. Who are the participants in the Master Slave pattern? Mention their roles.
78
Instruction for Conduction of Laboratory
1. Programs should be implemented using Java programming Language only
2. Record:
i. Left hand side:
Pattern Instance
UML Diagrams
Program Outcomes
ii. Right Hand side:
Case Study
Pattern Name
Pattern Intent
Participants Description
Pattern Context/ Applicabiltiy
Implementation (Java code)
Program Output
Applications
3. Data Sheet:
Name of the Pattern
Case Study
Pattern Instance
UML Diagrams
Java Code