Você está na página 1de 78

SVETA KUMARI. USN. No.

:1NZ08MCA18

INTRODUCTION

The Three Models:

It is often useful to model a system from three related but different


viewpoints, each capturing important aspects of the system, but all required for
a complete description.

The class model represents the static, structural, data aspects of a system.

The state model represents the temporal behavioral,”control” aspect of a


system.

The interaction model represents the collaboration of individual objects, the


interaction

aspects of a system.

Pattern:

A Pattern for software architecture describes a particular recurring design


problem that arises in a specific design contexts, and presents a well-proven
generic scheme for its solution. The solution scheme is specified by describing
its constituents components, their responsibilities and relationships, and the
ways in which they collaborate.

Pattern Categories:

To refine classification, patterns are classified into three groups:

• Architectural patterns
• Design Patterns
• Idioms

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

An architectural pattern expresses a fundamental structural organization


schema for software system. It provides a set of predefined subsystems,
specifies their relationships and includes rules and guidelines for organizing the
relationships between them.

A design pattern provides a schema for refining the subsystems or


components of a software system, or the relationships between them. It
describes a commonly-recurring structure of communicating components that
solve a general design problem within a particular context.

An idiom is a low-level pattern specific to a programming language. An


idiom describes how to implement particular aspects of components or the
relationships between them using the features of the given language.

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Lab Set

EXPERT

1. Using the UML Drawing Tool by implementing the code in Java


demonstrate the Expert Design Pattern.
An Expert pattern is useful in maintaining encapsulation of information,
it promotes low coupling and also provides highly cohesive classes which can
cause a class to become excessively complex.

Class Diagram:

Sales ProductDescription
total : float price : float = 43.89f

getTotal() getPrice()

SalesLineItem
SaleCounter quantity : int = 100

main() getSubTotal()

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

UseCase Diagram:

Product Specification

Customer
Choose Product with Qty

Shop Keeper

Make Subtotal of Lineitem

Total Bill

Sequence Diagram:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sales SalesLine Item Product Specification

1: Subtotal

2: Qty

3: Price

4: description

5: UPC

6: price(UPC)

7: Subtotal

8: Total

Code Implementatio

Product Description.java:

import java.io.*;

public class ProductDescription

private float price=43.89f;

public float getPrice ()

return price;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

SalesCounter.java:

import java.io.*;

public class SaleCounter

public static void main (String [] args)

float total;

Sales s=new Sales();

total=s.getTotal();

System.out.println ("Total sale is: "+total);

Sales .java:

import java.io.*;

public class Sales

private float total;

public float getTotal()

ProductDescription pd=new ProductDescription ();

SalesLineItem sli=new SalesLineItem ();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

total=(pd.getPrice()*sli.getSubTotal());

return total;

SalesLineItem:

public class SalesLineItem

private int quantity=100;

public int getSubTotal()

return quantity;

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CONTROLLER

2. Using the UML Drawing Tool by implementing the code in Java


demonstrate the Controller Design Pattern.
The Model View Controller architectural pattern divides an interactive
application into three components. The model contains the core functionality
and data. Views display information to the user. Controllers handle user input.
Views and Controllers together comprise the user interface. A change
propagation mechanism ensures consistency between the user interface and the
model.

Class Diagram:

CalcView
IINITIAL_VALUE : String = "1"

reset() CalcMVC
getUserInput()
setTotal() main()
ShowError() CalcMVC()
addMultipleListener()
addClearListener() +theCalcView
CalcView()

+theCalcModel

CalcModel
INITIAL_VALUE : String = "1"
m_Total : BigInteger
+theCalcModel CalcController
CalcModel()
reset() CalcController()
multiplyBy()
setValue()
getValue()

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram:

CalcController CalcView CalcModel

1: Invokes

2: Invokes

3: Resets

4: Set values

5: Multiplies the values

6: Obtains Model

7: Reset

8: Gets User input

9: Set Total

10: Multiplies listeners

11: Clears the Listeners

12: Displays Error message

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Code Implementataion:

CalcModel.java:

import java.math.BigInteger;

public class CalcModel

private String INITIAL_VALUE = "1";

private BigInteger m_total;

public CalcModel()

reset();

public void reset()

m_total=new BigInteger(INITIAL_VALUE);

public void multiplyBy(String operand)

m_total = m_total.multiply(new BigInteger(operand));

public void setValue(String value)

m_total = new BigInteger(value);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public String getValue()

return m_total.toString();

CalcController.java:

import java.awt.event.*;

public class CalcController

private CalcModel m_model;

private CalcView m_view;

CalcController(CalcModel model, CalcView view)

m_model = model;

m_view = view;

view.addMultiplyListener(new MultiplyListener());

view.addClearListener(new ClearListener());

class MultiplyListener implements ActionListener

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public void actionPerformed(ActionEvent e)

String userInput = "";

try

userInput = m_view.getUserInput();

m_model.multiplyBy(userInput);

m_view.setTotal(m_model.getValue());

catch(NumberFormatException nfex)

m_view.ShowError("Bad Input:'"+userInput+"'");

class ClearListener implements ActionListener

public void actionPerformed(ActionEvent e)

m_model.reset();

m_view.reset();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CalcView.java:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class CalcView extends JFrame

private static final String INITIAL_VALUE = "1";

private JTextField m_userInputTf=new JTextField(5);

private JTextField m_totalTf = new JTextField(20);

private JButton m_multiplyBtn = new JButton("Multiply");

private JButton m_clearBtn = new JButton("Clear");

private CalcModel m_model;

CalcView(CalcModel model)

m_model = model;

m_model.setValue(INITIAL_VALUE);

m_totalTf.setText(m_model.getValue());

m_totalTf.setEditable(false);

JPanel content=new JPanel();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

content.setLayout(new FlowLayout());

content.add(new JLabel("INPUT"));

content.add(m_userInputTf);

content.add(m_multiplyBtn);

content.add(new JLabel("Total"));

content.add(m_totalTf);

content.add(m_clearBtn);

this.setContentPane(content);

this.pack();

this.setTitle("Simple Calc_MVC");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void reset()

m_totalTf.setText(INITIAL_VALUE);

public String getUserInput()

return m_userInputTf.getText();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public void setTotal(String newTotal)

m_totalTf.setText(newTotal);

public void ShowError(String errMsg)

JOptionPane.showMessageDialog(this,errMsg);

public void addMultiplyListener(ActionListener mul)

m_multiplyBtn.addActionListener(mul);

public void addClearListener(ActionListener cal)

m_clearBtn.addActionListener(cal);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CalcMVC.java:

import javax.swing.*;

public class CalcMVC

public static void main(String[] args)

CalcModel model = new CalcModel();

CalcView view = new CalcView(model);

CalcController controller = new CalcController(model,view);

view.setVisible(true);

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

PUBLISHER-SUBSCRIBER(OBSERVER)

3. Using the UML Drawing Tool by implementing the code in Java


demonstrate the Observer Design Pattern.

The Publisher-Subscriber design pattern helps to keep the state of


cooperating components synchronized. To achieve this it enables one-way
propagation of changes: one publisher notifies any number of subscribers about
changes to its state.

Class Diagram:
Concrete_Subject
name : String
price : float PriceObserver
price : float
Concrete_Subject()
getName() PriceObserver()
getPrice() Update()
setPrice()
setName()

Testobserver
NameObserver
name : String main()
Testobserver()
NameObserver()
Update()

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram:

TestObserver Concreat NameObserver PriceObserver


Subject

1.Invokes

2.Invokes

3.invokes

4.respones

Code Implementation:

Observer.java:

import java.util.Observable;

import java.util.Observer;

public class Concrete_Subject extends Observable

private String name;

private float price;

public Concrete_Subject(String name, float price)

this.name=name;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

this.price=price;

System.out.println("Concrete subject Created " +name+ " at "


+price);

public String getName()

return name;

public float getPrice()

return price;

public void setPrice(float price)

this.price=price;

setChanged();

notifyObservers(new Float(price));

public void setName(String name)

this.name=name;

setChanged();

notifyObservers(name);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

NameObserver.java:

import java.util.Observable;

import java.util.Observer;

public class NameObserver implements Observer

private String name;

public NameObserver()

name=null;

System.out.println("Name Observer Created: Name is "+name);

public void update(Observable obj, Object arg)

if(arg instanceof String)

name=(String)arg;

System.out.println("Name Observer:Name Changed to


"+name+ "\n");

else

System.out.println("NameObserver: Not Changed\n");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

PriceObserver.java:

import java.util.Observable;

import java.util.Observer;

public class PriceObserver implements Observer

private Float price;

public PriceObserver()

price=0f;

System.out.println("Price Observer Created is: " );

public void update(Observable obj, Object arg)

if(arg instanceof Float)

price=((Float)arg).floatValue();

System.out.println("\nPriceObserver: price changed to "


+price);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

else

System.out.println("\nPriceObserver: Not changed ");

TestObserver.java:

import java.io.*;

public class Testobserver

public static void main(String arg[])

Concrete_Subject s = new Concrete_Subject("Cornflakes",1.29f);

NameObserver nameobs=new NameObserver();

PriceObserver priceobs=new PriceObserver();

s.addObserver(nameobs);

s.addObserver(priceobs);

s.setName("Roasted Flakes");

s.setPrice(41.50f);

s.setPrice(9.50f);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

s.setName("Sugar");

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

COMMAND

4.Using the UML Drawing Tool by implementing the code in Java


demonstrate the Command Design Pattern.

The Command Processor design pattern separates the request for a


service from the execution. A command processor component manages requests
as separate objects, schedules their execution, and provides additional services
as the storing of request objects for later undo.

Class Diagram:
ItemManager

setCom mand()
Command process()
Interface

execute()

AddCommand DeleteCommand
Comm andTest
AddCommand() DeleteCommand()
execute() execute() main()

Item Category
categories : HashMap items : HashMap
desc : String desc : String

Item() Category()
getDesc() getDesc()
add() add()
delete() delete()

Dynamics:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

The following diagram shows a typical scenario of the Command


Processor pattern implementing an undo mechanism. A request to capitalize a
selected word arrives, is performed and then undone. The following steps occur:

• The controller accepts the request from the user within its event loop and
creates a ‘capitalize’ command object.
• The controller transfers the new command object to the command processor
for execution and further handling.
• The command processor activates the execution of the command and stores it
for later undo.
• The capitalize command retrieves the currently- selected text from its supplier,
stores the text and its position in the document, and asks the supplier to
actually capitalize the selection.
• After accepting an undo request, the controller transfers this request to the
command processor. The command processor invokes the undo procedure of
the most recent command.
• The capitalize command resets the supplier to the previous state, by replacing
the saved text in its original position.
• If no further activity is required or possible of the command, the command
processor deletes the command object.

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram:

Client Invokes Controller Executor Executor

Command Test Item Manager Command Add Command Delete


Interface Command

1: Invokes

2: Executes

3: Add

4: Delete

Code Implementation:

AddCommand.java

import java.util.HashMap;

public class AddCommand implements CommandInterface

Category cat;

Item item;

public AddCommand(Item i, Category c)

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

item=i;

cat=c;

public void execute()

item.add(cat);

cat.add(item);

Category.java:

import java.util.HashMap;

public class Category

private HashMap items;

private String desc;

public Category(String s)

desc=s;

items=new HashMap();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public String getDesc()

return desc;

public void add(Item i)

items.put(i.getDesc(),i);

System.out.println("Item "+i.getDesc()+" has been added to the


"+getDesc()+" Category");

public void delete(Item i)

items.remove(i.getDesc());

System.out.println("Item " +i.getDesc()+" has been deleted from


the "+getDesc()+" Category");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CommandInterface:

public interface CommandInterface

public void execute();

DeleteCommand:

import java.util.HashMap;

public class DeleteCommand implements CommandInterface

Category cat;

Item item;

public DeleteCommand(Item i, Category c)

item=i;

cat=c;

public void execute()

item.delete(cat);

cat.delete(item);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Item.java:

import java.util.HashMap;

public class Item

private HashMap categories;

private String desc;

public Item(String s)

desc=s;

categories=new HashMap();

public String getDesc()

return desc;

public void add(Category cat)

categories.put(cat.getDesc(),cat);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public void delete(Category cat)

categories.remove(cat.getDesc());

ItemManager.java:

import java.util.HashMap;

public class ItemManager

CommandInterface command;

public void setCommand(CommandInterface c)

command=c;

public void process()

command.execute();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CommandTest.java:

import java.util.HashMap;

public class CommandTest

public static void main(String[] args)

Item CD=new Item("A Beautiful Mind");

Category catCD=new Category("CD");

CommandInterface command=new AddCommand(CD,catCD);

ItemManager manager=new ItemManager();

manager.setCommand(command);

manager.process();

CD=new Item("Classical");

catCD=new Category("CD");

catCD=new Category("CD");

command=new AddCommand(CD,catCD);

manager.setCommand(command);

manager.process();

command=new DeleteCommand(CD,catCD);

manager.setCommand(command);

manager.process();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

FARWARDER-RECEIVER

5. Using the UML Drawing Tool by implementing the code in Java demonstrate
the Forward-Receive Design Pattern.

The Forwarder-Receiver design pattern provides transparent interprocess


communication for software systems with a peer-to-peer interaction model. It
introduces forwarders and receivers to decouple peers from the underlying
communication mechanisms.

Class Diagram:

Client

main()

Message
Receiver Forwarder
sender : String
myName : String data : String myName : String

Receiver() Message() Forwarder()


unMarshal() marshal()
receive() +theForwarder deliver()
receiveMsg() +theReceiver
sendMsg()

Entry Server
destinationId : String
portNr : int run()
main()
Entry()
dest()
port()

Dynamics:

The following scenario illustrates Forwarder-Receiver structure. Two


peers P1 and P2 communicate with each other. P1 uses a forwarder Forw1 and a

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

receiver Recv1. P2 handles all messages transfers with a forwarder Forw2 and a
receiver Recv2:

• P1 request a service from a remote peer P2. For this purpose, it sends the
request to its forwarder Forw1 and specifies the name of the recipient.
• Forw1 determines the physical location of the remote peer and marshals the
message.
• Forw1 delivers the message to the remote receiver Recv2.

• At some earlier time P2 has requested its receiver Recv2 to wait for an
incoming request. Now, Recv2 receives the message arriving from Forw1.
• Recv2 unmarshals the message and forwards it to its peer P2.
• Meanwhile, P1 calls its receiver Recv1 to wait for a response.
• P2 performs the requested service, and sends the result and the name of the
recipient P1 to the forwarder Forw2. The forwarder marshals the result and
delivers it Recv1.
• Recv1 receives the response from p2, unmarshals it and determines it to P1

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram:
Peer Forwarder Receiver Receiver2 Forwarder Peer
P1 Forw1 Recv1 Recv2 Forw2 P2

1: recvMsg

2: reqService

3: sendMsg

4: Marshal

5: DeliverMsg

6: receive

7: unMarshal

8: DeliverMsg

9: receiveMsg

10: sendMsg

11: marshal

12: DeliverMsg

13: Receive

14: unMarshal

15: DeliverMsg

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Code Implementation:

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.OutputStream;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

import java.io.UnsupportedEncodingException;

import java.net.Socket;

public class Forwarder

private String myName;

private Socket s;

private OutputStream oStr;

public Forwarder(String theName)

System.out.println("\nFORWARDER-CLASS CREATED........!");

myName=theName;

private byte[] marshal(Message theMsg)

byte[] returnValue=null;

int i,emptySequence;

String str;

emptySequence=10-theMsg.sender.length();

str=" "+theMsg.sender;

for(i=0;i<emptySequence;i++)

str+=" ";

str+=theMsg.data;

System.out.println("\nForwarder "+str);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

try

returnValue=str.getBytes("UTF-8");

catch (UnsupportedEncodingException e)

System.out.println("\nData-Forward : "+returnValue);

return returnValue;

private void deliver(String theDest, byte[] data)

try

Entry entry;

if(theDest.equals("Client"))

entry=new Entry("127.0.0.1",8888);

System.out.println("\nSERVER---->FORWARDER");

else

entry=new Entry("127.0.0.1",9999);

System.out.println("\nCLIENT---->FORWARDER");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

s=new Socket(entry.dest(),entry.port());

System.out.println("\nCatching "+entry.dest()+entry.port());

oStr=s.getOutputStream();

oStr.write(data);

oStr.flush();

oStr.close();

s.close();

catch (Exception e)

public void sendMsg(String theDest, Message theMsg)

deliver(theDest,marshal(theMsg));

Message.java:

public class Message

public String sender;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public String data;

public Message(String theSender, String rawData)

sender=theSender;

data=rawData;

Receiver.java:

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.net.ServerSocket;

import java.net.Socket;

public class Receiver

private String myName;

private ServerSocket srvS;

private Socket s;

private InputStream iStr;

public Receiver(String theName)

System.out.println("\nRECEIVER-CLASS CREATED...........!");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

myName=theName;

public Message unMarshal(byte[] anArray)

String str="Reciever one",sender,data;

System.out.println("\nRECEIVER: "+str);

sender=str.substring(0,9);

System.out.println("\nSENDER: "+sender);

data=str.substring(10);

Message msg=new Message(sender.trim(),data);

return msg;

private byte[] receive()

int val;

byte buffer[]=null;

try

Entry entry;

if(myName.equals("Client"))

entry=new Entry("127.0.0.1",8888);

System.out.println("\nCLIENT------->RECEIVER");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

else

entry=new Entry("127.0.0.1",9999);

System.out.println("\nSERVER------->RECEIVER");

srvS=new ServerSocket(entry.port());

s=srvS.accept();

iStr=s.getInputStream();

val=iStr.read();

buffer=new byte[val];

iStr.read(buffer);

System.out.println("\nDATA-RECEIVED : "+buffer);

try

System.out.println("\nUNMARSHAL:"+new
String(buffer,"UTF-8"));

catch (UnsupportedEncodingException e1)

e1.printStackTrace();

iStr.close();

s.close();

srvS.close();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

catch (Exception e)

System.out.println("\nA Error Occured "+e.getMessage());

return buffer;

public Message receiveMsg()

return unMarshal(receive());

Server.java:

public class Server extends Thread

Receiver r;

Forwarder f;

public void run()

System.out.println("\nSERVER-CLASS
CREATED.....................!!");

Message result=null;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

r=new Receiver("Server");

result=r.receiveMsg();

System.out.println("\nSERVER-RESULT : "+result.sender);

f=new Forwarder("Server");

Message msg=new Message("Server","I AM ALIVE...............!");

f.sendMsg("Client",msg);

public static void main(String[] args)

Server aServer=new Server();

aServer.start();

Client.java:

public class Client

public static void main(String[] args)

Forwarder f=new Forwarder (new String("Client"));

Message msg=new Message ("Client","Helloooooooo............");

f.sendMsg("Server",msg);

Message result=null;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Receiver r=new Receiver (new String("Client"));

result=r.receiveMsg();

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

CLIENT-DISPATCHER-SERVER

6.Using the UML Drawing Tool by implementing the code in Java


demonstrate the Client-Dispatcher Design Pattern.

The Client-Dispatcher-Server design pattern introduces an intermediate


layer between clients and servers, the dispatcher component. It provides
location transparency by means of a name service, and hides the details of the
establishment of the communication connection between clients and servers.

Class-Diagram:
Service
Client nameOfservice : String PrintService
nameOfServer : String
doTask() Service()
Client() Service() PrintService()
Service()

NotFound

NotFound()

Dispatcher
registry : Hashtable = new Hashtable ClientDispatcher
rnd : Random = new Random(123456)+theDispatcher
main()
registry()
ClientDispatcher()
locate()
Dispatcher()

Dynamics:

A typical scenario for the Client-Dispatcher-Server design pattern


includes the following phases:

• A server registers itself with the dispatcher component.

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

• At a later time, a client asks the dispatcher for a communication channel to a


specified server.

• The dispatcher looks up the server that is associated with the name specified
by the client in its registry.
• The dispatcher establishes a communication link to the server. If it is able to
initiate the connection successfully, it returns the communication channel to
the client. If not, it sends the client an error message.

• The client uses the communication channel to send a request directly to the
server.
• After recognizing the incoming request, the server executes the appropriate
service.
• When the service execution is completed, the server sends the results back to
the client.

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram
Client Dispatcher Server

1: registerService

2: getChannel

3: locateServer

4: establishChannel

5: acceptConnection
6: connectionAccepted
7: sendRequest

8: receiveRequest
9: runService

10: serviceServed

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Code Implementation:

Client:

import java.util.*;

import java.io.*;

public class Client

public void doTask()

Service s;

try

s=ClientDispatcher.disp.locate("PrintService");

s.Service();

catch (NotFound n)

System.out.println("Not avaliable");

try

s=ClientDispatcher.disp.locate("MailService");

s.Service();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

catch (NotFound n)

System.out.println("Not avaliable");

try

s=ClientDispatcher.disp.locate("DrawService");

s.Service();

catch (NotFound n)

System.out.println("Not avaliable");

Dispatcher.java:

import java.io.*;

import java.util.*;

public class Dispatcher

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Hashtable registry = new Hashtable();

Random rnd = new Random(123456);

public void registry(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 locate(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);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

NotFound.java:

import java.io.*;

import java.util.*;

class NotFound extends Exception

Service.java:

import java.io.*;

import java.util.*;

abstract class Service

String nameOfservice;

String nameOfServer;

public Service(String SVC, String SRV)

nameOfservice=SVC;

nameOfServer=SRV;

ClientDispatcher.disp.registry(nameOfservice,this);

abstract public void Service();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

PrintService.java:

import java.util.*;

import java.io.*;

public class PrintService extends Service

public PrintService(String SVC, String SRV)

super(SVC,SRV);

public void Service()

System.out.println("Service"+nameOfservice+" by "
+nameOfServer);

Client-Dispatcher.java

import java.util.*;

import java.io.*;

public class ClientDispatcher

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public static Dispatcher disp=new Dispatcher();

public static void main(String args[])

Service s1=new PrintService("PrintService","Server1");

Service s2=new PrintService("MailService","Server2");

//Service s3=new PrintService("DrawService","Server3");

Client client=new Client();

client.doTask();

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

PROXY

7. Using the UML Drawing Tool by implementing the code in Java


demonstrate the Proxy Design Pattern.

The Proxy design pattern makes the clients of a component communicate


with a representative rather than to the component itself. Introducing such a
placeholder can serve many purposes, including enhanced efficiency, easier
access and protection from unauthorized access.

Class Diagram:
AbstractClass
str : String = ""

AbstractClass()

Client

main()
Client()

Proxy Server
+theProxy
ServerName() getservice()
Proxy() Server()

Dynamics:

The following diagram shows a typical dynamic scenario of a proxy


structure.

• While working on its tack the client asks the proxy to carry out a service.
• The proxy receives the incoming service request and pre-processes it. This
pre-processing involves actions such as looking up the address of the original,

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

or checking a local cache to see if the requested information is already


available.
• If the proxy has to consult the original to fulfill the request, it forwards the
request to the original using the proper communication protocols and security
measures.
• The original accepts the request and fulfills it. It sends the response back to the
proxy.
• The proxy receives the response. Before or after transferring it to the client it
may carry out additional post-processing actions such as caching the result,
calling the destructor of the original or releasing a lock on a resource.

Sequence Diagram:

Client Proxy Server

1: Request for Service

2: Find in the cache

3: Get the service from Server

4: Get the Service

5: Cache the new information

6: Get the Service done

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Collaboration Diagram

Server
3: Responding with the Service

6: Cached Service will be given


Proxy 2: Request for the S ervice
4: Caches the Service

1: Request for Service


Client 5: Retrying to access the service

Code Implementation:

AbstractClas.java

import java.io.*;

public class AbstractClass

public String str ;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public AbstractClass() throws IOException

str="";

Proxy.java:

import java.io.*;

public class Proxy extends AbstractClass

public AbstractClass theAbstractClass;

public Server m_Server;

public Client m_client;

public Proxy() throws IOException

public void ServerName() throws IOException

System.out.println(" Proxy===>");

if(str=="")

System.out.println(" Trying to get the service from server ");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

m_Server=new Server();

str=m_Server.getservice();

System.out.println(" Server says " +str);

else

System.out.println(" Proxy also cached your request ");

System.out.println(" Proxy says "+str);

Server.java

import java.io.*;

public class Server extends AbstractClass

public Proxy m_proxy;

public String getservice()

System.out.println(" Server Initializing");

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

str=" Hello.........!";

return(str);

Client.java:

import java.io.*;

public class Client

public Proxy m_Proxy;

public static void main(String args[]) throws IOException

Proxy m_Proxy1=new Proxy();

System.out.println("\n\n\n 1st time Establishing Connection");

m_Proxy1.ServerName();

System.out.println("\n\n\n 2nd time Retrying for Connection");

m_Proxy1.ServerName();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

FACADE

8.Using the UML Drawing Tool by implementing the code in Java


demonstrate the Facade Design Pattern.

A Façade is a Pattern you can take a complex subsystem and make it


easier to use by implementing a Façade class that provides one, more reasonable
Interface to handle the Classes and its corresponding sub classes.

Class Diagram:
SubClasses

Credit Loan Bank

HasGoodCredit() HasNoBadLoans() HasSufficientSavings()

Customer
MainApp Mortgage
Name : String
main() isEligible()
Customer()

implement Facade
Main

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequence Diagram:
MainApp Mortgage Bank Credit Loan

1: Invokes

2: Invokes

3: Invokes

4: Invokes

5: Response

Code Imlementation:

Bank.java:

import java.io.*;

public class Bank

public boolean HasSufficientSavings(Customer c, int amount)

System.out.println("Check Bank for " +c.Name);

return true;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Credit.java:

import java.io.*;

public class Credit

public boolean HasGoodCredit(Customer c)

System.out.println("Check credit for " +c.Name);

return true;

Customer.java:

import java.io.*;

public class Customer

String Name;

public Customer(String name)

this.Name=name;

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Loan.java:

import java.io.*;

public class Loan

public boolean HasNoBadLoans(Customer c)

System.out.println("Check Loans for "+c.Name);

return true;

Mortgage.java:

import java.io.*;

public class Mortgage

private Credit _credit=new Credit();

private Loan _loan= new Loan();

private Bank _bank=new Bank();

public boolean IsEligible(Customer cust, int amount) throws IOException

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

System.out.println(cust.Name+" applies for " +amount+" loan\n");

boolean eligible=true;

if(!_bank.HasSufficientSavings(cust,amount))

eligible=false;

else if(!_loan.HasNoBadLoans(cust))

eligible=false;

else if(!_credit.HasGoodCredit(cust))

eligible=false;

return eligible;

MainApp.java:

import java.io.*;

import java.util.*;

public class MainApp

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public static void main(String args[]) throws IOException

Mortgage mortgage=new Mortgage();

Customer customer=new Customer("ANUSHA");

boolean eligible=mortgage.IsEligible(customer,12500);

System.out.println("\n"+customer.Name+" has been " +(eligible?"


Approved ":" Rejected "));

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

POLYMORPHISM

9. Using the UML Drawing Tool by implementing the code in Java


demonstrate the Polymorphism Design Pattern.

Polymorphism is a method of single objects taking different forms. It is


easier and more reliable then using explicit selection logic, it also helps to add
additional behaviors later on, increases the number classes in a design.

Interface Polymorphism:

Actor

act()
Actor()

HappyActor +theActor
SadActor
act()
HappyActor() act()
SadActor()

Transmogrify

main()
Transmogrify()
Stage

Change()
PerformPlay()
Stage()

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Sequential Interface polymorphism:

Interface
Poly
pi : float = 3.14f

area()

Square Circ le
final2 : float final1 : float

area() area()

Tes tP oly

main()

Sequence Diagram:

Stage HappyActor SadActor


Transmogrify

1: invokes

2: request

3: request

4: response

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Code Implementation:

Interface Polymorphism:

InterfacePoly.java:

public interface InterfacePoly

float pi = 3.14f;

public void area(float f);

Circle.java:

import java.util.*;

public class Circle implements InterfacePoly

private float final1;

public void area(float radius)

final1=pi*radius*radius;

System.out.println("Area of Circle= "+final1);

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Square.java:

import java.io.*;

public class Square implements InterfacePoly

private float final2;

public void area(float side)

final2=side*side;

System.out.println("Area of the Square= "+final2);

Testpoly.java

import java.util.*;

public class TestPoly

public static void main(String args[])

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Circle c1=new Circle();

Square s1=new Square();

c1.area(10.2f);

s1.area(7.8f);

Code Implementation:

Actor.java:

abstract class Actor

public abstract void act() ;

HappyActor.java:

import java.io.*;

public class HappyActor extends Actor

public void act()

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

System.out.println("HAPPY-ACTOR");

SadActor.java:

import java.io.*;

public class SadActor extends Actor

public void act()

System.out.println("SAD-ACTOR");

Stage.java:

class Stage

public Actor actor=new HappyActor();

public void change()

actor=new SadActor();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

public void PerformPlay()

actor.act();

Transmogrify.java:

import java.util.*;

public class Transmogrify

public static void main(String[] args)

Stage stage=new Stage();

stage.PerformPlay();

stage.change();

stage.PerformPlay();

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

Output:

07MCA57 PAGE: DEPARTMENT OF CA, NHCE


SVETA KUMARI. USN. No.:1NZ08MCA18

07MCA57 PAGE: DEPARTMENT OF CA, NHCE