Escolar Documentos
Profissional Documentos
Cultura Documentos
:1NZ08MCA18
INTRODUCTION
The class model represents the static, structural, data aspects of a system.
aspects of a system.
Pattern:
Pattern Categories:
• Architectural patterns
• Design Patterns
• Idioms
Lab Set
EXPERT
Class Diagram:
Sales ProductDescription
total : float price : float = 43.89f
getTotal() getPrice()
SalesLineItem
SaleCounter quantity : int = 100
main() getSubTotal()
UseCase Diagram:
Product Specification
Customer
Choose Product with Qty
Shop Keeper
Total Bill
Sequence Diagram:
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.*;
return price;
SalesCounter.java:
import java.io.*;
float total;
total=s.getTotal();
Sales .java:
import java.io.*;
total=(pd.getPrice()*sli.getSubTotal());
return total;
SalesLineItem:
return quantity;
Output:
CONTROLLER
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()
Sequence Diagram:
1: Invokes
2: Invokes
3: Resets
4: Set values
6: Obtains Model
7: Reset
9: Set Total
Code Implementataion:
CalcModel.java:
import java.math.BigInteger;
public CalcModel()
reset();
m_total=new BigInteger(INITIAL_VALUE);
return m_total.toString();
CalcController.java:
import java.awt.event.*;
m_model = model;
m_view = view;
view.addMultiplyListener(new MultiplyListener());
view.addClearListener(new ClearListener());
try
userInput = m_view.getUserInput();
m_model.multiplyBy(userInput);
m_view.setTotal(m_model.getValue());
catch(NumberFormatException nfex)
m_view.ShowError("Bad Input:'"+userInput+"'");
m_model.reset();
m_view.reset();
CalcView.java:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
CalcView(CalcModel model)
m_model = model;
m_model.setValue(INITIAL_VALUE);
m_totalTf.setText(m_model.getValue());
m_totalTf.setEditable(false);
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);
m_totalTf.setText(INITIAL_VALUE);
return m_userInputTf.getText();
m_totalTf.setText(newTotal);
JOptionPane.showMessageDialog(this,errMsg);
m_multiplyBtn.addActionListener(mul);
m_clearBtn.addActionListener(cal);
CalcMVC.java:
import javax.swing.*;
view.setVisible(true);
Output:
PUBLISHER-SUBSCRIBER(OBSERVER)
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()
Sequence Diagram:
1.Invokes
2.Invokes
3.invokes
4.respones
Code Implementation:
Observer.java:
import java.util.Observable;
import java.util.Observer;
this.name=name;
this.price=price;
return name;
return price;
this.price=price;
setChanged();
notifyObservers(new Float(price));
this.name=name;
setChanged();
notifyObservers(name);
NameObserver.java:
import java.util.Observable;
import java.util.Observer;
public NameObserver()
name=null;
name=(String)arg;
else
PriceObserver.java:
import java.util.Observable;
import java.util.Observer;
public PriceObserver()
price=0f;
price=((Float)arg).floatValue();
else
TestObserver.java:
import java.io.*;
s.addObserver(nameobs);
s.addObserver(priceobs);
s.setName("Roasted Flakes");
s.setPrice(41.50f);
s.setPrice(9.50f);
s.setName("Sugar");
Output:
COMMAND
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:
• 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.
Sequence Diagram:
1: Invokes
2: Executes
3: Add
4: Delete
Code Implementation:
AddCommand.java
import java.util.HashMap;
Category cat;
Item item;
item=i;
cat=c;
item.add(cat);
cat.add(item);
Category.java:
import java.util.HashMap;
public Category(String s)
desc=s;
items=new HashMap();
return desc;
items.put(i.getDesc(),i);
items.remove(i.getDesc());
CommandInterface:
DeleteCommand:
import java.util.HashMap;
Category cat;
Item item;
item=i;
cat=c;
item.delete(cat);
cat.delete(item);
Item.java:
import java.util.HashMap;
public Item(String s)
desc=s;
categories=new HashMap();
return desc;
categories.put(cat.getDesc(),cat);
categories.remove(cat.getDesc());
ItemManager.java:
import java.util.HashMap;
CommandInterface command;
command=c;
command.execute();
CommandTest.java:
import java.util.HashMap;
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();
Output:
FARWARDER-RECEIVER
5. Using the UML Drawing Tool by implementing the code in Java demonstrate
the Forward-Receive Design Pattern.
Class Diagram:
Client
main()
Message
Receiver Forwarder
sender : String
myName : String data : String myName : String
Entry Server
destinationId : String
portNr : int run()
main()
Entry()
dest()
port()
Dynamics:
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
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
Code Implementation:
Entry.java:
destinationId=theDest;
portNr=thePort;
return destinationId;
return portNr;
Forwarder.java:
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
private Socket s;
System.out.println("\nFORWARDER-CLASS CREATED........!");
myName=theName;
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);
try
returnValue=str.getBytes("UTF-8");
catch (UnsupportedEncodingException e)
System.out.println("\nData-Forward : "+returnValue);
return returnValue;
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");
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)
deliver(theDest,marshal(theMsg));
Message.java:
sender=theSender;
data=rawData;
Receiver.java:
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
private Socket s;
System.out.println("\nRECEIVER-CLASS CREATED...........!");
myName=theName;
System.out.println("\nRECEIVER: "+str);
sender=str.substring(0,9);
System.out.println("\nSENDER: "+sender);
data=str.substring(10);
return msg;
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");
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"));
e1.printStackTrace();
iStr.close();
s.close();
srvS.close();
catch (Exception e)
return buffer;
return unMarshal(receive());
Server.java:
Receiver r;
Forwarder f;
System.out.println("\nSERVER-CLASS
CREATED.....................!!");
Message result=null;
r=new Receiver("Server");
result=r.receiveMsg();
System.out.println("\nSERVER-RESULT : "+result.sender);
f=new Forwarder("Server");
f.sendMsg("Client",msg);
aServer.start();
Client.java:
f.sendMsg("Server",msg);
Message result=null;
result=r.receiveMsg();
Output:
CLIENT-DISPATCHER-SERVER
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:
• 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.
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
Code Implementation:
Client:
import java.util.*;
import java.io.*;
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();
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.*;
Vector v=(Vector)registry.get(SVC);
if(v==null)
v=new Vector();
registry.put(SVC,v);
v.addElement(obj);
Vector v=(Vector)registry.get(SVC);
int i=rnd.nextInt()%v.size();
return(Service)v.elementAt(i);
NotFound.java:
import java.io.*;
import java.util.*;
Service.java:
import java.io.*;
import java.util.*;
String nameOfservice;
String nameOfServer;
nameOfservice=SVC;
nameOfServer=SRV;
ClientDispatcher.disp.registry(nameOfservice,this);
PrintService.java:
import java.util.*;
import java.io.*;
super(SVC,SRV);
System.out.println("Service"+nameOfservice+" by "
+nameOfServer);
Client-Dispatcher.java
import java.util.*;
import java.io.*;
client.doTask();
Output:
PROXY
Class Diagram:
AbstractClass
str : String = ""
AbstractClass()
Client
main()
Client()
Proxy Server
+theProxy
ServerName() getservice()
Proxy() Server()
Dynamics:
• 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,
Sequence Diagram:
Collaboration Diagram
Server
3: Responding with the Service
Code Implementation:
AbstractClas.java
import java.io.*;
str="";
Proxy.java:
import java.io.*;
System.out.println(" Proxy===>");
if(str=="")
m_Server=new Server();
str=m_Server.getservice();
else
Server.java
import java.io.*;
str=" Hello.........!";
return(str);
Client.java:
import java.io.*;
m_Proxy1.ServerName();
m_Proxy1.ServerName();
Output:
FACADE
Class Diagram:
SubClasses
Customer
MainApp Mortgage
Name : String
main() isEligible()
Customer()
implement Facade
Main
Sequence Diagram:
MainApp Mortgage Bank Credit Loan
1: Invokes
2: Invokes
3: Invokes
4: Invokes
5: Response
Code Imlementation:
Bank.java:
import java.io.*;
return true;
Credit.java:
import java.io.*;
return true;
Customer.java:
import java.io.*;
String Name;
this.Name=name;
Loan.java:
import java.io.*;
return true;
Mortgage.java:
import java.io.*;
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.*;
boolean eligible=mortgage.IsEligible(customer,12500);
Output:
POLYMORPHISM
Interface Polymorphism:
Actor
act()
Actor()
HappyActor +theActor
SadActor
act()
HappyActor() act()
SadActor()
Transmogrify
main()
Transmogrify()
Stage
Change()
PerformPlay()
Stage()
Interface
Poly
pi : float = 3.14f
area()
Square Circ le
final2 : float final1 : float
area() area()
Tes tP oly
main()
Sequence Diagram:
1: invokes
2: request
3: request
4: response
Code Implementation:
Interface Polymorphism:
InterfacePoly.java:
float pi = 3.14f;
Circle.java:
import java.util.*;
final1=pi*radius*radius;
Square.java:
import java.io.*;
final2=side*side;
Testpoly.java
import java.util.*;
c1.area(10.2f);
s1.area(7.8f);
Code Implementation:
Actor.java:
HappyActor.java:
import java.io.*;
System.out.println("HAPPY-ACTOR");
SadActor.java:
import java.io.*;
System.out.println("SAD-ACTOR");
Stage.java:
class Stage
actor=new SadActor();
actor.act();
Transmogrify.java:
import java.util.*;
stage.PerformPlay();
stage.change();
stage.PerformPlay();
Output: