dp lab manual
TRANSCRIPT
-
8/11/2019 DP Lab Manual
1/90
UML & DP LAB MANUAL
List of Experiments
S.no Exp.no Name of the Experiment Page no Date
1. 1. To create a UML diagram of ATM Application.
2. 2. To create a UML diagram of LIBRARYMANAGEMENT SYSTEM.
3. 3. To create a UML diagram of ONLINE BOOK
SHOP.
4. 4. To create a UML diagram of RAILWAYRESERVATION SYSTEM.
5. 5. To create a UML diagram of BANKINGSYSTEM.
6. 6. To Design a DOCUMENT EDITOR
7. 7. Using UML design ABSTRACT FACTORYdesign pattern.
8. 8. Using UML design BUILDER design pattern.
9. 9. Using UML design FAADE design pattern.
10. 10. Using UML design BRIDGE design pattern.
11. 11. Using UML design DECORATER designpattern.
12. 12. User gives a print command from a worddocument .Design to represent this chain of
responsibility design pattern
-
8/11/2019 DP Lab Manual
2/90
UML DI GR MS
Description about UML
The Unified Modeling Language (UML) is a graphical language for visualizing, specifying,
constructing, and documenting the artifacts of a software-intensive system.
The UML offers a standard way to write a system's blueprints, including conceptual things such
as business processes and system functions as well as concrete things such as programming
language statements, database schemas, and reusable software components."
The Relationships are Further classified as Follows:
-
8/11/2019 DP Lab Manual
3/90
The Diagrams are further Classified as Follows:
Types of UML Diagrams
1. USECASE Diagrams
2. CLASS Diagrams
3. OBJECT Diagrams
4. COMPONENT Diagrams
5. DEPLOYEMENT Diagrams
6. SEQUENCE Diagrams
7. COLLABORATION Diagrams
8. ACTIVITY Diagrams
9. STATECHART Diagrams.
Structural Diagrams
-
8/11/2019 DP Lab Manual
4/90
1. Use Case Diagram displays the relationship among actors and use cases.
A use case diagram displays the relationship among actors and use
cases. The two main components of a use case diagram are use cases and
actors.
2. Class Diagram models class structure and contents using design elements such as
classes, packages and objects. It also displays relationships such as containment,
inheritance, associations and others.
Classes are composed of three things: a name, attributes, and operations. Below isan example of a class.
3. Object Diagram are sometimes referred as Instance diagrams and they arevery similar to Class diagrams .They are used to show how a system would look
like at a given time .
Object diagram is a discrete entity with a well-defined boundary that encapsulates
state and behavior.
4. Component Diagramdisplays the high level packaged structure of the codeitself. Dependencies among components are shown, including source code
components, binary code components, and executable components. Some
http://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/use_case.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/use_case.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/class.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/class.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/class.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/use_case.htm -
8/11/2019 DP Lab Manual
5/90
components exist at compile time, at link time, at run times well as at more than
one time.
5. Deployment Diagramdisplays the configuration of run-time processing elementsand the software components, processes, and objects that live on them. Software
component instances represent run-time manifestations of code units.
Behavioral Diagrams:
6. Sequence Diagramdisplays the time sequence of the objects participating in theinteraction. This consists of the vertical dimension (time) and horizontal dimension
(different objects)
The example below shows an object of class 1 start the behavior by sending a
message to an object of class 2. Messages pass between the different objects untilthe object of class 1 receives the final message
http://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/interaction.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/interaction.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/interaction.htm -
8/11/2019 DP Lab Manual
6/90
7. Collaboration Diagramdisplays an interaction organized around the objects andtheir links to one another. Numbers are used to show the sequence of messages.
8. Activity Diagramdisplays a special state diagram where most of the states are actionstates and most of the transitions are triggered by completion of the actions in the source
states. This diagram focuses on flows driven by internal processing.
9.State Diagram displays the sequences of states that an object of an interaction goesthrough during its life in response to received stimuli, together with its responses and
actions.
http://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/activity.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/activity.htmhttp://pigseye.kennesaw.edu/~dbraun/csis4650/A&D/UML_tutorial/activity.htm -
8/11/2019 DP Lab Manual
7/90
EXP NO: 1
1. To create a UML diagram of ATM APPLI CATION.
AIM: To create a UML diagram of ATM APPLICATION.
DESCRIPTION:
In this ATM application, it mainly deals with the operations the client used to
perform on the ATM machine. In order to perform operations the client must contain a valid
ATM card with a valid Pin number. The types of operations the client or card holder can perform
on the given ATM machine are Balance Enquiry, Withdraw, Deposit, Password change etc.
After performing the above mentioned operations the corresponding Database must be updated
in the Bank Database.
Diagrams
1. USECASE Diagram
Actors
Card Holder
ATM Machine
Bank Database
Usecases
Insert Card, Eject Card
-
8/11/2019 DP Lab Manual
8/90
-
8/11/2019 DP Lab Manual
9/90
2.Class Diagram
The identified Classes are
Customer
Bank Server
User Interface
Account
Class diagrams are arguably the most used UML diagram type. It is the main building
block of any Object Oriented solution. It shows the classes in a system, attributes and operations
of each class and the relationship between each class.
3.Component DiagramThe Components Are
Customer
Bank Server
User Interface
Account
-
8/11/2019 DP Lab Manual
10/90
A component Diagram displays the Structural relationship of components of a software
system. These are mostly used when working with complex systems that have many components.
Components communicate with each other using Interfaces. The interfaces are liked using
connectors.A component diagram represents a modular part of a system that encapsulates its
contents.
The component diagram can show components, dependencies between components and
the way in which they are connected to.
4.Deployement Diagram
The Nodes in the Deployement Diagram are
Customer
Bank Server
User Interface
A Deployment Diagram shows the hardware of your system and the software in that hardware.
Deployment Diagrams are useful when your software solution is deployed across multiple
machines with each having a unique configuration.
The Deployment diagrams are represented using nodes. There are two types of nodes
Device Node
Processer Node
Web
Client
ATM
BankDb
Printer
-
8/11/2019 DP Lab Manual
11/90
5. Sequence Diagram
The objects in the Sequence Diagram are
Customer object
Account object
Bank server object
Sequence Diagrams in UML shows how object interact with each other and the order those
interactions occur. It is important to note that they show the interactions for a particular scenario. The
Processes are represented vertically and interactions are shown as arrows.
Customer
Atm
Machine
BankDb
Printing
Machine
Browser
-
8/11/2019 DP Lab Manual
12/90
6. Collaboration Diagram
The objects in the Collaboration diagram are same as of Sequence diagram. They are Customer object
Bank Server object
Account object
Collaboration Diagrams are very similar to Activity Diagrams. While activity
diagrams show a sequence of processes, Collaboration overview sequence of diagrams. It
is similar to sequence diagrams but the focus is on messages passed between objects. The
same information can be represented using a sequence diagram and different objects.
:client :atm :controller :database
InsertCardVerifyCard
ValidPin
SelectTransaction
EnterAmount CheckBalance
SufficientBalance
WithDrawAmount
UpdateAmount
AmountUpdated
CloseTransaction
-
8/11/2019 DP Lab Manual
13/90
The Collaboration diagram describes interactions among objects in terms of
sequenced messages; these are also called as Communication Diagr4ams or Interaction
Diagrams.
7. Activity Diagram
The objects in the Activity Diagram are
Customer object
Account object
Bank server object
Activity Diagrams represent workflows in a graphical way. They can be used todescribe business workflow or the operational workflow of any component in a system. Sometimes
activity diagrams are used as an alternative to State machine Diagrams.
The Activity Diagrams are used to display the sequence of activities. They are
nothing but the graphical representations of workflows of stepwise activities and actions.
:client:atm
:controller :database
1: InsertCard
2: VerifyCard
4: SelectTransaction5: EnterAmount
6: CheckBalance
7: SufficientBalance
8: WithDrawAmount
9: UpdateAmount
10: AmountUpdated
11: CloseTransact ion
3: ValidPin
-
8/11/2019 DP Lab Manual
14/90
-
8/11/2019 DP Lab Manual
15/90
-
8/11/2019 DP Lab Manual
16/90
EXP NO: 2
2. To create a UML diagram of L I BRARY MANAGEMENT SYSTEM.
AIM: To create a UML diagram of LIBRARY MANAGEMENT SYSTEM.
DESCRIPTION:
In the LIBRARY Management System, the student or any member can enquire
for a membership, and the membership will be issued by the Librarian. Any member having the
membership card can do the following operations: checks for the availability of books, request
for book issue, return the book, pay fine if any. Whereas the Librarian will do the following
operations: Issue Membership, Collects book, Collects Fine, Maintain Book Records, Update
Student account details etc.
Diagrams
1. USECASE Diagram
Actors
Member
Librarian
Use cases
Enquiry for Membership, Request for Book Issue, Search Book
Select Book, Return Book, Pay fine
Issue Membership, Issue Book
Collect Books, Collect fine
Maintain Book Records, Update Membership Details.
Use case diagram gives a graphical overview of the actors involved in a system,
different functions needed by those actors and how these different functions are interacted.
Use case diagrams are the most known type of the Behavioral UML diagrams.
-
8/11/2019 DP Lab Manual
17/90
2. Class Diagram
The identified Classes are
Member
Librarian
Database
MembershipEnquiry
RequestForIssue
FinePayment
RequestForReturn
Member
Issue
GrantMembership
UpdateAccount
AddAccount
CheckAvailability
Librarian
-
8/11/2019 DP Lab Manual
18/90
Class diagrams are arguably the most used UML diagram type. It is the main building
block of any Object Oriented solution. It shows the classes in a system, attributes and operations
of each class and the relationship between each class.
3. Component Diagram
The Components Are
Member
Librarian
Database
A component Diagram displays the Structural relationship of components of a software
system. These are mostly used when working with complex systems that have many components.
Components communicate with each other using Interfaces. The interfaces are liked using
connectors.
A component diagram represents a modular part of a system that encapsulates its
contents.
The component diagram can show components, dependencies between components and
the way in which they are connected to.
-
8/11/2019 DP Lab Manual
19/90
4. Deployment Diagram
The Nodes in the Deployment Diagram are
Member
Librarian
Database
A Deployment Diagram shows the hardware of your system and the software in that hardware.
Deployment Diagrams are useful when your software solution is deployed across multiplemachines with each having a unique configuration.
The Deployment diagrams are represented using nodes. There are two types of nodes
Device Node
Processer Node
Member Librarian
LibraryDb
-
8/11/2019 DP Lab Manual
20/90
5. Sequence Diagram
The objects in the Sequence Diagram are
Member object
Librarian object
Database object
Sequence Diagrams in UML shows how object interact with each other and the order those
interactions occur. It is important to note that they show the interactions for a particular scenario. The
Processes are represented vertically and interactions are shown as arrows.
MemberLibrarian
LibraryDB
-
8/11/2019 DP Lab Manual
21/90
:member :librarian : LibraryDb
RequestMembership
AddAccount
AccountAddedAccountCreated with Id
SelectBook
RequestIssueCheckAvailability
BookAvailable
IssueGranted
ReturnBookCheckForDues
PayFine
CollectFine
FinePayed
UpdateAccount
UpdateAccount
AccountUpdated
Acknowledgement
LogOut
LoggedOut
-
8/11/2019 DP Lab Manual
22/90
6. Collaboration Diagram
The objects in the Collaboration diagram are same as of Sequence diagram. They are
Member object
Librarian object
Database object
Collaboration Diagrams are very similar to Activity Diagrams. While activity
diagrams show a sequence of processes, Collaboration overview sequence of diagrams. It
is similar to sequence diagrams but the focus is on messages passed between objects. The
same information can be represented using a sequence diagram and different objects.
The Collaboration diagram describes interactions among objects in terms of
sequenced messages; these are also called as Communication Diagr4ams or Interaction
Diagrams.
7. Activity Diagram
The objects in the Activity Diagram are
Member object
Librarian object
Database object
:member :librarian
: Library
Db
1: RequestMembership
2: AddAccount
3: AccountAdded
4: AccountCreated with Id
5: SelectBook
6: RequestIssue
7: CheckAvailability
8: BookAvailable
9: IssueGranted
10: UpdateAccount
11: ReturnBook
12: CheckForDues
13: CollectFine
14: PayFine
15: FinePayed
16: UpdateAccount
17: AccountUpdated
18: Acknowledgement
19: LogOut
20: LoggedOut
-
8/11/2019 DP Lab Manual
23/90
Activity Diagrams represent workflows in a graphical way. They can be used to
describe business workflow or the operational workflow of any component in a system. Sometimes
activity diagrams are used as an alternative to State machine Diagrams.
The Activity Diagrams are used to display the sequence of activities. They are
nothing but the graphical representations of workflows of stepwise activities and actions.
8. State Chart Diagram
State machine diagrams are similar to Activity Diagrams although notations and usage changes a
bit. They are sometimes known as state diagrams or State Chart Diagrams as well. They are very
useful to describe the Behavior of objects that act different according to the state they are at the
moment.
-
8/11/2019 DP Lab Manual
24/90
They are most commonly used to model the dynamic behavior of classes.
-
8/11/2019 DP Lab Manual
25/90
EXP NO: 3
3. To create a UML diagram of ONL INE BOOK SHOP.
AIM: To create a UML diagram of ONLINE BOOK SHOP.
DESCRIPTION:
In the ONLINE BOOK SHOP, the User may Login to any website containing
Book Shopping, and can perform the following operations: Search for a particular Book,
selecting a book, adding a Book to a cart, Updating Cart, Purchase Book, Giving Feedback,
Checking out Payment details etc. Whereas the Admin will be there Controlling the Operations
performed by the User. The Operations done by the Admin are: Adding new Items to the Cart,
Modifying Customer Order, and Checking Availability etc. The Bank Server will be connected
to the Website to Check the Payment Details.
Diagrams
1. USECASE Diagram
Actors
User
Admin
Visitor
Credit Card Company
Use cases
Logging into the website, Selecting book, Adding Book to the Cart
Updating the Cart, Giving feedback, Payment
Updating Items in the website, Verifying Customer details
Creating Accounts, Deleting Accounts, Receiving amount
Sending Notification to Admin etc.
Use case diagram gives a graphical overview of the actors involved in a system,
different functions needed by those actors and how these different functions are interacted.
Use case diagrams are the most known type of the Behavioral UML diagrams.
-
8/11/2019 DP Lab Manual
26/90
2. Class Diagram
The identified Classes are
Customer Admin
Books
Credit Card
Login
ViewCategory
SlectBook
AddToCart
RemoveFromCart
EditCart
ViewCart
PurchaseBook
FeedBack
Customer
RecievePayment
CreateAccount
AddCategory
UpdateCart
AddBook
CreditCard
Company
ViewCustomerDetails
Admin
-
8/11/2019 DP Lab Manual
27/90
Class diagrams are arguably the most used UML diagram type. It is the main building
block of any Object Oriented solution. It shows the classes in a system, attributes and operations
of each class and the relationship between each class.
3. Component Diagram
The Components Are
Customer
Admin
Books
Credit Card
A component Diagram displays the Structural relationship of components of a software
system. These are mostly used when working with complex systems that have many components.
Components communicate with each other using Interfaces. The interfaces are liked using
connectors.
A component diagram represents a modular part of a system that encapsulates its
contents.
-
8/11/2019 DP Lab Manual
28/90
The component diagram can show components, dependencies between components and
the way in which they are connected to.
4. Deployment Diagram
The Nodes in the Deployment Diagram are
Customer
Admin
Books
Credit Card
A Deployment Diagram shows the hardware of your system and the software in that hardware.
Deployment Diagrams are useful when your software solution is deployed across multiple
machines with each having a unique configuration.
The Deployment diagrams are represented using nodes. There are two types of nodes
Device Node
Processer Node
Customer CreditCard
Product Admin
-
8/11/2019 DP Lab Manual
29/90
5. Sequence Diagram
The objects in the Sequence Diagram are
Customer object
Books object
Admin object
Credit Card object
Sequence Diagrams in UML shows how object interact with each other and the order those
interactions occur. It is important to note that they show the interactions for a particular scenario. The
Processes are represented vertically and interactions are shown as arrows.
Admin
Customer
Product
Credit
Card
-
8/11/2019 DP Lab Manual
30/90
6. Collaboration Diagram
The objects in the Collaboration diagram are same as of Sequence diagram. They are
Customer object
Books object
Admin object
C:CustomerS B:BooksA:Admin C':CreditCard
Login
OpenCustomerDetails
SelectCategory
ViewDeatails
PurchaseBook
SelectBook
AddItemToCart
ViewBooks
UpdateCart
CheckCreditCardPayment
PaymentIsDone
SendNotification
FeedBack
Terminate
-
8/11/2019 DP Lab Manual
31/90
Credit Card object
Collaboration Diagrams are very similar to Activity Diagrams. While activity
diagrams show a sequence of processes, Collaboration overview sequence of diagrams. It
is similar to sequence diagrams but the focus is on messages passed between objects. The
same information can be represented using a sequence diagram and different objects.
The Collaboration diagram describes interactions among objects in terms of
sequenced messages; these are also called as Communication Diagr4ams or Interaction
Diagrams.
7. Activity Diagram
The objects in the Activity Diagram are
Customer object
Books object
Admin object
Credit Card object
Activity Diagrams represent workflows in a graphical way. They can be used to
describe business workflow or the operational workflow of any component in a system. Sometimes
activity diagrams are used as an alternative to State machine Diagrams.
The Activity Diagrams are used to display the sequence of activities. They are
nothing but the graphical representations of workflows of stepwise activities and actions.
C:Custo
merS
B:Books
A:Admin C':CreditCard
1: Login
2: OpenCustomerDetails
3: SelectCategory
4: ViewDeatails
5: SelectBook
6: AddItemToCart
7: PurchaseBook
8: ViewBooks
9: UpdateCart
10: Payment
11: CheckCreditCardDetails
12: PaymentIsDone
13: SendNotification
14: FeedBack
15: Terminate
-
8/11/2019 DP Lab Manual
32/90
8. State Chart Diagram
State machine diagrams are similar to Activity Diagrams although notations and usage changes a
bit. They are sometimes known as state diagrams or State Chart Diagrams as well. They are veryuseful to describe the Behavior of objects that act different according to the state they are at the
moment. They are most commonly used to model the dynamic behavior of classes.
-
8/11/2019 DP Lab Manual
33/90
EXP NO: 4
4. To create a UML diagram of RAI LWAY RESERVATION SYSTEM .
AIM: To create a UML diagram of RAILWAY RESERVATION SYSTEM.
DESCRIPTION:
In the RAILWAY RESERVATION SYSTEM, the Passenger will Logon to the
Railway Website and checks the Availability of trains by specifying the details, if there is
Availability then he will request for Booking, Make Payment and the ticket will be printed. The
Railway Server present on the other side will check the details and accept payment and confirm
booking. In the Bank Database the Account will be updated and the Notification will be sent to
the Customer.
Diagrams
1. USECASE Diagram
Actors
Passenger
Railway server
Bank Database
Use cases
Login, Select Train, check Availability
Select Language
Enter Train Details, Enter User Information
Request for Booking, Make Payment, Print Ticket
Update Account Database
Check User Information, Accept payment, confirm booking, Send Notification to
the Passenger
Use case diagram gives a graphical overview of the actors involved in a system,
different functions needed by those actors and how these different functions are interacted.
Use case diagrams are the most known type of the Behavioral UML diagrams.
-
8/11/2019 DP Lab Manual
34/90
-
8/11/2019 DP Lab Manual
35/90
Class diagrams are arguably the most used UML diagram type. It is the main building
block of any Object Oriented solution. It shows the classes in a system, attributes and operations
of each class and the relationship between each class.
3. Component Diagram
The Components Are
Customer
Bank Server User Interface
Account
A component Diagram displays the Structural relationship of components of a software
system. These are mostly used when working with complex systems that have many components.
-
8/11/2019 DP Lab Manual
36/90
Components communicate with each other using Interfaces. The interfaces are liked using
connectors.
A component diagram represents a modular part of a system that encapsulates its
contents.
The component diagram can show components, dependencies between components and
the way in which they are connected to.
4. Deployment Diagram
The Nodes in the Deployment Diagram are
Passenger
Bank Database
Railway Server
User Interface
A Deployment Diagram shows the hardware of your system and the software in that hardware.
Deployment Diagrams are useful when your software solution is deployed across multiple
machines with each having a unique configuration.
The Deployment diagrams are represented using nodes. There are two types of nodes
Device Node
Processer Node
Passenger User interface
Database
-
8/11/2019 DP Lab Manual
37/90
5. Sequence Diagram
The objects in the Sequence Diagram are
Passenger object
Railway Controller object
Railway Database object
Sequence Diagrams in UML shows how object interact with each other and the order
those interactions occur. It is important to note that they show the interactions for a particular
scenario. The Processes are represented vertically and interactions are shown as arrows.
Printer
RailwayReservation
webserver
UserInterface
Passenger1 Passenger2
-
8/11/2019 DP Lab Manual
38/90
6. Collaboration Diagram
The objects in the Collaboration diagram are same as of Sequence diagram. They are
Passenger object
Railway Controller object
Railway Database object
Collaboration Diagrams are very similar to Activity Diagrams. While activity
diagrams show a sequence of processes, Collaboration overview sequence of diagrams. It
is similar to sequence diagrams but the focus is on messages passed between objects. The
same information can be represented using a sequence diagram and different objects.
The Collaboration diagram describes interactions among objects in terms of
sequenced messages; these are also called as Communication Diagr4ams or Interaction
Diagrams.
Passenger Login ReservationClerk
Databse
Enter name and passwordsending name and password
verify
show home page
Book ticket
verify ticket
Ask for Account
8.Enter Account
send account number
verify
successfully verified
successfully reserved
Issue tiicket
-
8/11/2019 DP Lab Manual
39/90
7. Activity Diagram
The objects in the Activity Diagram are
Passenger object
Railway Controller object
Railway Database object
Activity Diagrams represent workflows in a graphical way. They can be used todescribe business workflow or the operational workflow of any component in a system. Sometimes
activity diagrams are used as an alternative to State machine Diagrams.
The Activity Diagrams are used to display the sequence of activities. They are
nothing but the graphical representations of workflows of stepwise activities and actions.
8. State Chart Diagram
State machine diagrams are similar to Activity Diagrams although notations and usage changes a
bit. They are sometimes known as state diagrams or State Chart Diagrams as well. They are very
useful to describe the Behavior of objects that act different according to the state they are at the
moment.
Databse
Passenger
Login
Reservation Clerk
3: verify6: verify ticket 10: verify
1: Enter name and password
2: sending name and password4: show home page
7: Ask for Account number12: successfully reserved
13: Issue tiicket
5: Book ticket8: 8.Enter Account number
9: send account number
11: successfully verified
-
8/11/2019 DP Lab Manual
40/90
They are most commonly used to model the dynamic behavior of classes.
EXP NO: 5
5. To create a UML diagram of BANKI NG SYSTEM .
AIM: To create a UML diagram ofBANKING SYSTEM.
-
8/11/2019 DP Lab Manual
41/90
DESCRIPTION:
In this BANKING SYSTEM, the Customer will Login to the Specified Bank
Server. If he is not having any Account before then he will request for a new Account. A
Customer having an Account can Perform the following operations: Balance Enquiry, Select
Transactions (Deposit Amount, Withdraw amount, Transfer Amount, etc.). After selecting he can
perform the Transactions and Finally Logout from his Account. The Bank Server will verify the
Details, Creates new Accounts, Maintain Account Details, and Update Account Information.
Diagrams
1. USECASE Diagram
Actors
Customer
Bank Server
Use cases
Login, Logout
Select Language
Enter Details
Perform Transactions (Withdraw, Deposit, Transfer, Balance Enquiry)
Update Account Database
Terminate Transaction
Use case diagram gives a graphical overview of the actors involved in a system,
different functions needed by those actors and how these different functions are interacted.
Use case diagrams are the most known type of the Behavioral UML diagrams.
-
8/11/2019 DP Lab Manual
42/90
2. Class Diagram
The identified Classes are
Customer
Bank Server
User Interface
Account
Class diagrams are arguably the most used UML diagram type. It is the main building
block of any Object Oriented solution. It shows the classes in a system, attributes and operations
of each class and the relationship between each class.
BankServer
login
balance enquiry
request for new account
select transaction
perform transaction
view details
feedback
terminate account
customer
verify details
fill form to open account
maintain account details
check availability
show details
update account info
-
8/11/2019 DP Lab Manual
43/90
3.
Component DiagramThe Components Are
Customer
Bank Server
User Interface
Account
A component Diagram displays the Structural relationship of components of a software
system. These are mostly used when working with complex systems that have many components.
Components communicate with each other using Interfaces. The interfaces are liked using
connectors.
A component diagram represents a modular part of a system that encapsulates its
contents.
-
8/11/2019 DP Lab Manual
44/90
The component diagram can show components, dependencies between components and
the way in which they are connected to.
4. Deployment Diagram
The Nodes in the Deployment Diagram are
Customer
Bank Server
User Interface
A Deployment Diagram shows the hardware of your system and the software in that hardware.Deployment Diagrams are useful when your software solution is deployed across multiple
machines with each having a unique configuration.
The Deployment diagrams are represented using nodes. There are two types of nodes
Device Node
Processer Node
customer Bank server
user interfaceAccount
-
8/11/2019 DP Lab Manual
45/90
5. Sequence Diagram
The objects in the Sequence Diagram are
Customer object
Account object
Bank server object
Sequence Diagrams in UML shows how object interact with each other and the order thoseinteractions occur. It is important to note that they show the interactions for a particular scenario. The
Processes are represented vertically and interactions are shown as arrows.
customer
bank server
user
interface
-
8/11/2019 DP Lab Manual
46/90
6. Collaboration Diagram
The objects in the Collaboration diagram are same as of Sequence diagram. They are
Customer object Bank Server object
Account object
Collaboration Diagrams are very similar to Activity Diagrams. While activity
diagrams show a sequence of processes, Collaboration overview sequence of diagrams. It
C:customer A:account B:bankserver
1: login 2: validate
3: validating4: list transaction details
5: select transaction
6: perform transaction 7: check details
8: checking
9: account valid
10: transaction completed
11: ask question to continue or not
12: NO 13: update account
14: account updated
15: transaction successfull
16: logout
17: terminate transaction
18: terminate
-
8/11/2019 DP Lab Manual
47/90
is similar to sequence diagrams but the focus is on messages passed between objects. The
same information can be represented using a sequence diagram and different objects.
The Collaboration diagram describes interactions among objects in terms of
sequenced messages; these are also called as Communication Diagr4ams or Interaction
Diagrams.
7. Activity Diagram
The objects in the Activity Diagram are
Customer object
Account object
Bank server object
Activity Diagrams represent workflows in a graphical way. They can be used to
describe business workflow or the operational workflow of any component in a system. Sometimes
activity diagrams are used as an alternative to State machine Diagrams.
The Activity Diagrams are used to display the sequence of activities. They are
nothing but the graphical representations of workflows of stepwise activities and actions.
A:accou
nt
C:custo
mer
B:banks
erver
1: login
2: validate
3: validating
4: list transaction details
5: select transaction
6: perform transaction
7: check details
8: checking
9: account valid
10: transaction completed
11: ask question to continue or not
12: NO
13: update account
14: account updated15: transaction successfull
16: logout
17: terminate transaction
18: terminate
-
8/11/2019 DP Lab Manual
48/90
8. State Chart Diagram
State machine diagrams are similar to Activity Diagrams although notations and usage changes a
bit. They are sometimes known as state diagrams or State Chart Diagrams as well. They are very
useful to describe the Behavior of objects that act different according to the state they are at the
moment.
They are most commonly used to model the dynamic behavior of classes.
-
8/11/2019 DP Lab Manual
49/90
EXP NO: 6
6. To Design a DOCUMENT EDI TOR.
AIM: To design a DOCUMENT EDITOR in LEXI.
DESCRIPTION:
While Designing a DOCUMENT EDITOR in LEXI we will examine the
following seven problems. They are:
1. Document structure
2. Formatting
3. Embellishment
4. Multiple look & feels
5. Multiple window systems
6. User operations
7. Spelling checking & hyphenation.
Let us discuss in detail about each problem in detail:
1.Document Structure:
Goals:
present documents visual aspects
drawing, hit detection, alignment
support physical structure (e.g., lines, columns)
Constraints/forces:
treat text & graphics uniformly
no distinction between one & many
Recursive Composit ion
a common way to represent hierarchically structured information
-
8/11/2019 DP Lab Manual
50/90
Glyphs:
an abstract class for all objects that can appear in a document structure
three basic responsibilities, they know
how to draw themselves, what space they occupy, and their children and parent
Composite Pattern:
captures the essence of recursive composition in object-oriented terms
-
8/11/2019 DP Lab Manual
51/90
2.Formatting:
A structure that corresponds to a properly formatted document
Representation and formatting are distinct
the ability to capture the documents physical structure doesnt tell us how to
arrive at a particular structure
here, well restrict formatting to mean breaking a collection of glyphs in to lines
Encapsulating the formatting algorithm:
-
8/11/2019 DP Lab Manual
52/90
o keep formatting algorithms completely independent of the document
structure
o make it is easy to change the formatting algorithm
o Well define a separate class hierarchy for objects that encapsulate
formatting algorithms
Compositor and Composition
o Well define a Compositor class for objects that can encapsulate a
formatting algorithm
o The glyphs Compositor formats are the children of a special Glyph
subclass called Composition
o When the composition needs formatting, it calls its compositors Compose
operation
o Each Compositor subclass can implement a different line breaking
algorithm
Compositor and Composition (cont.)o The Compositor-Composition class split ensures a strong
separation between code that supports the documents physical
structure and the code for different formatting algorithms
Strategy pattern
o intent: encapsulating an algorithm in an object
o Compositors are strategies. A composition is the context for a
compositor strategy
-
8/11/2019 DP Lab Manual
53/90
3.Embell ishing the User I nter face:
Considering adds a border around the text editing area and scrollbars that let the
user view the different parts of the page here
Transparent Enclosure
o inheritance-based approach will result in some problems
o Composition, ScrollableComposition, BorderedScrollableComposition,
o object composition offers a potentially more workable and flexible
extension mechanism
o object composition (cont.)
o Border and Scroller should be a subclass of Glyph
o two notions
o single-child (single-component) composition
o compatible interfaces
Monoglyph
o We can apply the concept of transparent enclosure to all glyphs that
embellish other glyphs
o the class, Monoglyph
Decorator Pattern
o captures class and object relationships that support embellishment bytransparent enclosure
void MonoGlyph::Draw(Window* w) {
-
8/11/2019 DP Lab Manual
54/90
_component-> Draw(w);
}
void Border:: Draw(Window * w) {
MonoGlyph::Draw(w);
DrawBorder(w);
}
4.Supporting Mul tiple Look-and-Feel Standards:
Design to support the look-and-feel changing at run-time
Abstracting Object Creation
o widgets
o two sets of widget glyph classes for this purpose
a set of abstract glyph subclasses for each category of widget glyph (e.g.,
ScrollBar)
a set of concrete subclasses for each abstract subclass that implementdifferent look-and-feel standards (e.g., MotifScrollBar and PMScrollBar
Abstracting Object Creation (cont.)
o Lexis needs a way to determine the look-and-feel standard being targeted
o We must avoid making explicit constructor calls
o We must also be able to replace an entire widget set easily
o We can achieve both by abstracting the process of object creation
-
8/11/2019 DP Lab Manual
55/90
Factories and Product Classes
o Factories create product objects
o The example
Abstract Factory Pattern
o capture how to create families of related product objects without instantiating
classes directly
-
8/11/2019 DP Lab Manual
56/90
5.Supporting M ul tiple Window Systems:
Wed like Lexis to run on many existing window systems having different
programming interfaces
Can we use an Abstract Factory?
o As the different programming interfaces on these existing window
systems, the Abstract Factory pattern doesnt work
o We need a uniform set of windowing abstractions that lets us takedifferent window system implementations and slide any one of them under
a common interface
Encapsulating Implementation Dependencies
o The Window class interface encapsulates the things windows tend to do across
window systems
o The Window class is an abstract class
o Where does the implementation live?
Window and WindowImp
Bridge Pattern
o to allow separate class hierarchies to work together even as they evolve
independently
-
8/11/2019 DP Lab Manual
57/90
6.User Operations:
Requirements
o Lexi provides different user interfaces for the operations it supportedo These operations are implemented in many different classes
o Lexis supports undo and redo
The challenge is to come up with a simple and extensible mechanism that satisfies
all of these needs
Encapsulating a Request
-
8/11/2019 DP Lab Manual
58/90
o We could parameterize MenuItem with a function to call, but thats not a
complete solution
it doesnt address the undo/redo problem
its hard to associate state with a function
functions are hard to extent, and its hard to reuse part of them
o We should parameterize MenuItems with an object, not a function
Command Class and Subclasses
o The Command abstract class consists of a single abstract operation called
Execute
o MenuItem can store a Command object that encapsulates a request
o When a user choose a particular menu item, the MenuItem simply calls
Execute on its Command object to carry out the request
7.Spell ing Checking & Hyphenation:
-
8/11/2019 DP Lab Manual
59/90
-
8/11/2019 DP Lab Manual
60/90
examines words accumulated from character glyphs
At potential hyphenation point, inserts a...
class HyphenationVisitor : public Visitor {
public:
void visit (Character &);
void visit (Rectangle &);
void visit (Row &);
// etc. for all relevant Glyph subclasses
};
Structure:
-
8/11/2019 DP Lab Manual
61/90
DESIGN PATTERNS
DESIGN PATTERNS:
Design Patterns are the best solutions for the
re-occurring problems in the application programming environment.
DESCRIBING DESIGN PATTERNS:
The Design Patterns can be Described using the below 13 elements.
They are:
1. Pattern Name and Classification
2. Intent
3. Also Known As
4. Motivation5. Applicability
6. Structure
7. Participants
8. Collaborations
9. Consequences
10.Implementation
11.Sample Code
12.Known Users
13.Related Patterns
-
8/11/2019 DP Lab Manual
62/90
ORGANIZATION OF DP:
-
8/11/2019 DP Lab Manual
63/90
-
8/11/2019 DP Lab Manual
64/90
Appl icabi l i ty :
Use the Abstract Factory pattern when
a system should be independent of how its products are created, composed, andrepresented.
a system should be configured with one of multiple families of products.
a family of related product objects is designed to be used together, and you need toenforce this constraint.
you want to provide a class library of products, and you want to reveal just their
interfaces, not their implementations.
Structure:
-
8/11/2019 DP Lab Manual
65/90
-
8/11/2019 DP Lab Manual
66/90
build mazes take a MazeFactory as an argument so that the programmer can specify the classesof rooms, walls, and doors to construct.
class MazeFactory {public:
MazeFactory();virtual Maze* MakeMaze() const{ return new Maze; }virtual Wall* MakeWall() const{ return new Wall; }virtual Room* MakeRoom(int n) const{ return new Room(n); }virtual Door* MakeDoor(Room* r1, Room* r2) const{ return new Door(r1, r2); }};
Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* aMaze = factory.MakeMaze();Room* r1 = factory.MakeRoom(1);Room* r2 = factory.MakeRoom(2);Door* aDoor = factory.MakeDoor(r1, r2);aMaze->AddRoom(r1);aMaze->AddRoom(r2);r1->SetSide(North, factory.MakeWall());r1->SetSide(East, aDoor);r1->SetSide(South, factory.MakeWall());r1->SetSide (West, factory.MakeWall());r2->SetSide(North, factory.MakeWall());r2->SetSide(East, factory.MakeWall());
r2->SetSide(South, factory.MakeWall());r2->SetSide(West, aDoor);return aMaze;}
We can create EnchantedMazeFactory, a factory for enchanted mazes, by subclassing
MazeFactory. EnchantedMazeFactory will override different member functions and return
different subclasses of Room, Wall, etc.
class EnchantedMazeFactory : public MazeFactory {public:
EnchantedMazeFactory();virtual Room* MakeRoom(int n) const{ return new EnchantedRoom(n, CastSpell()); }virtual Door* MakeDoor(Room* r1, Room* r2) const{ return new DoorNeedingSpell(r1, r2); }protected:Spell* CastSpell() const;};
-
8/11/2019 DP Lab Manual
67/90
Know n Uses:
InterViews uses the "Kit" to denote AbstractFactory classes. ET++ uses the AbstractFactory pattern to achieve portability across different window systems
Related Patterns :
AbstractFactory classes are often implemented with factory methods but they
can also be implemented using
PrototypeA concrete factory is often a
singleton
Builder Creational Patterns.
-
8/11/2019 DP Lab Manual
68/90
EXP NO: 8
8.Using UML design BUILDER design pattern.
AIM: Using UML design BUILDER design pattern.
DESCRIPTION:
Pattern Name:Builder Design Pattern
Intent:Separate the construction of a complex object from its representation so that the
same construction process can create different representations.
Also Known As:
Motivation:A reader for the RTF (Rich Text Format) document exchange format should be able to
convert RTF to many textformats. The reader might convert RTF documents into plain ASCII
text or into a text widget that can be editedinteractively. The problem, however, is that the
number of possible conversions is open-ended. So it should beeasy to add a new conversionwithout modifying the reader.
A solution is to configure the RTFReader class with a TextConverter object that
converts RTF to another textual representation. As the RTFReader parses the RTF document, it
uses the TextConverter to perform the conversion
Applicability:
Use the Builder pattern when
-
8/11/2019 DP Lab Manual
69/90
the algorithm for creating a complex object should be independent of the parts that makeup the object and how they're assembled.
the construction process must allow different representations for the object that's
constructed.
Structure:
Participants:
Builder (TextConverter)specifies an abstract interface for creating parts of a Product object.
ConcreteBuilder (ASCIIConverter, TeXConverter, TextWidgetConverter)constructs and assembles parts of the product by implementing the Builder interface.defines and keeps track of the representation it creates.
provides an interface for retrieving the product (e.g., GetASCIIText, GetTextWidget). Director (RTFReader)
constructs an object using the Builder interface.
Product (ASCIIText, TeXText, TextWidget)represents the complex object under construction. ConcreteBuilder builds the product's
internal representation and defines the process by which it's assembled.
includes classes that define the constituent parts, including interfaces for assembling theparts into the final result.
Collaborations:
The client creates the Director object and configures it with the desired Builder object.
Director notifies the builder whenever a part of the product should be built.
Builder handles requests from the director and adds parts to the product
The client retrieves the product from the builder
-
8/11/2019 DP Lab Manual
70/90
Consequences:
Here are key consequences of the Builder pattern:
It lets you vary a product's internal representation
It isolates code for construction and representation. It gives you finer control over the construction process.
Implementation:
Typically there's an abstract Builder class that defines an operation for each component
that a director may ask it to create. The operations do nothing by default. A ConcreteBuilder
class overrides operations for components it's interested in creating.
Here are other implementation issues to consider:
1. Assembly and construction interface
2. Why no abstract class for products?
3.Empty methods as default in Builder.
Sample Code:
We'll define a variant of the CreateMaze member function that takes a builder of class
MazeBuilder as an argument. The MazeBuilder class defines the following interface for buildingmazes:
class MazeBuilder {public:virtual void BuildMaze() { }virtual void BuildRoom(int room) { }virtual void BuildDoor(int roomFrom, int roomTo) { }virtual Maze* GetMaze() { return 0; }protected:MazeBuilder();};
Given the MazeBuilder interface, we can change the CreateMaze member function to take thisbuilder as a parameter.
Maze* MazeGame::CreateMaze (MazeBuilder& builder) {builder.BuildMaze();builder.BuildRoom(1);
builder.BuildRoom(2);
builder.BuildDoor(1, 2);
return builder.GetMaze();
-
8/11/2019 DP Lab Manual
71/90
}
Known Users:
The RTF converter application is from ET++ . Its text building block uses a builder to
process text stored in the RTF format.
Builder is a common pattern in Smalltalk-80 .
Related Patterns:
Abstract Factory is similar to Builder in that it too may construct complex objects. The
primary difference is that the Builder pattern focuses on constructing a complex object step by
step. Abstract Factory's emphasis is on families of product objects (either simple or complex).
Builder returns the product as a final step, but as far as the Abstract Factory pattern is concerned,the product gets returned immediately.
A Composite is what the builder often builds.
Factory Method
Abstract Factory
-
8/11/2019 DP Lab Manual
72/90
EXP NO: 9
9.Using UML FACADE design design pattern.
AIM: Using UML FACADE design design pattern.
DESCRIPTION:
Pattern Name: Facade
Intent:
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Al so Known As:
Motivation:
Structuring a system into subsystems helps reduce complexity. A common design goalis to minimize the communication and dependencies between subsystems. One way to achieve
this goal is to introduce a facade object that provides a single, simplified interface to the more
general facilities of a subsystem.
Applicability:
Use the Facade pattern when
-
8/11/2019 DP Lab Manual
73/90
you want to provide a simple interface to a complex subsystem. Subsystems often getmore complex as they evolve. Most patterns, when applied, result in more and smaller
classes. This makes the subsystem more reusable and easier to customize, but it also
becomes harder to use for clients that don't need to customize it. A facade can provide asimple default view of the subsystem that is good enough for most clients. Only clients
needing more customizability will need to look beyond the facade. There are many dependencies between clients and the implementation classes of an
abstraction. Introduce a facade to decouple the subsystem from clients and othersubsystems, thereby promoting subsystem independence and portability.
You want to layer your subsystems. Use a facade to define an entry point to eachsubsystem level. If subsystems are dependent, then you can simplify the dependencies
between them by making them communicate with each other solely through theirFacades.
Structure:
Participants:
Facade (Compiler
o knows which subsystem classes are responsible for a request.o delegates client requests to appropriate subsystem objects.
subsystem classes (Scanner, Parser, ProgramNode, etc.)o implement subsystem functionality.o handle work assigned by the Facade object.o have no knowledge of the facade; that is, they keep no references to it.
Collaborations:
Clients communicate with the subsystem by sending requests to Facade, which forwardsthem to the appropriate subsystem object(s). Although the subsystem objects perform the actual
work, the facade may have to do work of its own to translate its interface to subsystem
interfaces.
Clients that use the facade don't have to access its subsystem objects directly
-
8/11/2019 DP Lab Manual
74/90
Consequences:
The Facade pattern offers the following benefits:
1. It shields clients from subsystem components, thereby reducing the number of objects
that clients deal with and making the subsystem easier to use.
2. It promotes weak coupling between the subsystem and its clients. Often the components
in a subsystem are strongly coupled. Weak coupling lets you vary the components of the
subsystem without affecting its clients. Facades help layer a system and the dependenciesbetween objects. They can eliminate complex or circular dependencies. This can be an
important consequence when the client and the subsystem are implemented
independently.
Reducing compilation dependencies is vital in large software systems. You want tosave time by minimizing recompilation when subsystem classes change. Reducing compilation
dependencies with facades can limit the recompilation needed for a small change in an importantsubsystem. A facade can also simplify porting systems to other platforms, because it's less likelythat building one subsystem requires building all others.
3. It doesn't prevent applications from using subsystem classes if they need to. Thus you canchoose between ease of use and generality.
Implementation:
Consider the following issues when implementing a facade:
1. Reducing client-subsystem coupling
2. .Public versus private subsystem classes.
Sample Code:
The compiler subsystem defines a {BytecodeStream} class that implements a stream of Bytecode objects.
A Bytecode object encapsulates a bytecode, which can specify machine instructions. The subsystem also
defines a Token class for objects that encapsulate tokens in the programming language.
The Scanner class takes a stream of characters and produces a stream of tokens, one token at a time.
class Scanner {public:Scanner(istream&);virtual ~Scanner();virtual Token& Scan();private:istream& _inputStream;};
The class Parser uses a ProgramNodeBuilder to construct a parse tree from a Scanner's tokens.
-
8/11/2019 DP Lab Manual
75/90
-
8/11/2019 DP Lab Manual
76/90
centralizing functionality that doesn't belong in any one of them. A mediator's colleagues are
aware of and communicate with the mediator instead of communicating with each other directly.
In contrast, a facade merely abstracts the interface to subsystem objects to make them easier touse; it doesn't define new functionality, and subsystem classes don't know about it.
Usually only one Facade object is required. Thus Facade objects are often Singletons
Flyweight Decorators
-
8/11/2019 DP Lab Manual
77/90
EXP NO: 10
10.Using UML design BRIDGE design pattern.
AIM: Using UML design BRIDGE design pattern.
DESCRIPTION:
Pattern Name: Bridge
Intent:
Decouple an abstraction from its implementation so that the two can vary independently
Also Known As: Handle/Body
Motivation:
When an abstraction can have one of several possible implementations, the usual way to
accommodate them is to use inheritance. An abstract class defines the interface to theabstraction, and concrete subclasses implement it in different ways. But this approach isn't
always flexible enough. Inheritance binds an implementation to the abstraction permanently,
which makes it difficult to modify, extend, and reuse abstractions and implementationsindependently.
-
8/11/2019 DP Lab Manual
78/90
Applicability:
Use the Bridge pattern when
you want to avoid a permanent binding between an abstraction and its implementation.This might be the case, for example, when the implementation must be selected or
switched at run-time.
both the abstractions and their implementations should be extensible by subclassing. Inthis case, the Bridge pattern lets you combine the different abstractions and
implementations and extend them independently.
changes in the implementation of an abstraction should have no impact on clients; that is,their code should not have to be recompiled.
(C++) you want to hide the implementation of an abstraction completely from clients. In
C++ the representation of a class is visible in the class interface.
you have a proliferation of classes as shown earlier in the first Motivation diagram. Sucha class hierarchy indicates the need for splitting an object into two parts. Rumbaugh usesthe term "nested generalizations" to refer to such class hierarchies.
you want to share an implementation among multiple objects (perhaps using referencecounting), and this fact should be hidden from the client. A simple example is Coplien's
String class, in which multiple objects can share the same string representation.
Structure:
-
8/11/2019 DP Lab Manual
79/90
Participants:
Abstraction (Window)
o
defines the abstraction's interface.o maintains a reference to an object of type Implementor.
RefinedAbstraction (IconWindow)Extends the interface defined by Abstraction.
Implementor (WindowImp)
o defines the interface for implementation classes. This interface doesn't have tocorrespond exactly to
o Abstraction's interface; in fact the two interfaces can be quite different. Typicallythe Implementor interface provides only primitive operations, and Abstraction
defines higher-level operations based on these primitives.
ConcreteImplementor (XWindowImp, PMWindowImp)
o implements the Implementor interface and defines its concreteImplementations.
Collaborations:
Abstraction forwards client requests to its Implementor object
Consequences:
The Bridge pattern has the following consequences:
Decoupling interface and implementation
Improved extensibility
Hiding implementation details from clients
Implementation:
Consider the following implementation issues when applying the Bridge pattern:
1. Only one Implementor
2. Creating the right Implementor object
3. Sharing implementors
4. Using multiple inheritance
Sample Code:
The following C++ code implements the Window/WindowImp example from the Motivation
section. The Window class defines the window abstraction for client applications:
class Window {
-
8/11/2019 DP Lab Manual
80/90
public:Window(View* contents);// requests handled by windowvirtual void DrawContents();virtual void Open();
virtual void Close();virtual void Iconify();virtual void Deiconify();// requests forwarded to implementationvirtual void SetOrigin(const Point& at);virtual void SetExtent(const Point& extent);virtual void Raise();virtual void Lower();virtual void DrawLine(const Point&, const Point&);virtual void DrawRect(const Point&, const Point&);virtual void DrawPolygon(const Point[], int n);virtual void DrawText(const char*, const Point&);protected:WindowImp* GetWindowImp();View* GetView();private:WindowImp* _imp;View* _contents; // the window's contents};
Window maintains a reference to a WindowImp, the abstract class that declares an interface tothe underlying windowing system.
class WindowImp {public:virtual void ImpTop() = 0;virtual void ImpBottom() = 0;virtual void ImpSetExtent(const Point&) = 0;virtual void ImpSetOrigin(const Point&) = 0;virtual void DeviceRect(Coord, Coord, Coord, Coord) = 0;virtual void DeviceText(const char*, Coord, Coord) = 0;virtual void DeviceBitmap(const char*, Coord, Coord) = 0;// lots more functions for drawing on windows...
protected:WindowImp();};
Known Users:
-
8/11/2019 DP Lab Manual
81/90
The ET++ Window/WindowPort design extends the Bridge pattern in that the WindowPort
also keeps a reference back to the Window. The WindowPort implementor class uses this
reference to notify Window about WindowPortspecific events: the arrival of input events,window resizes, etc.
libg++ defines classes that implement common data structures, such as Set, LinkedSet,
HashSet, LinkedList, and HashTable. Set is an abstract class that defines a set abstraction, whileLinkedList and HashTable are concrete implementors for a linked list and a hash table,respectively
NeXT's AppKit uses the Bridge pattern in the implementation and display of graphical
images. An image can be represented in several different ways.
Related Patterns:
An Abstract Factorycan create and configure a particular Bridge.
The Adapter pattern is geared toward making unrelated classes work together. It is usually
applied to systems after they're designed. Bridge, on the other hand, is used up-front in a design
to let abstractions and implementations vary independently.
Composite
Adapter
-
8/11/2019 DP Lab Manual
82/90
EXP NO: 11
11.Using UML design DECORATORdesign pattern.
AIM: Using UML design DECORATOR design pattern.
DESCRIPTION:
Pattern Name: Decorator
Intent:
Attach additional responsibilities to an object dynamically. Decorators provide a flexiblealternative to subclassing for extending functionality.
Also Known As: WRAPPER
Motivation:
One way to add responsibilities is with inheritance. Inheriting a border from anotherclass puts a border around every subclass instance. This is inflexible, however, because the
choice of border is made statically. A client can't control how and when to decorate the
component with a border.
A more flexible approach is to enclose the component in another object that adds theborder. The enclosing object is called a decorator. The decorator conforms to the interface of
the component.
Applicability:
Use Decorator
to add responsibilities to individual objects dynamically and transparently, that is,without affecting other objects.
-
8/11/2019 DP Lab Manual
83/90
for responsibilities that can be withdrawn.
when extension by subclassing is impractical. Sometimes a large number of independentextensions are
possible and would produce an explosion of subclasses to support every combination. Or
a class definition may be hidden or otherwise unavailable for subclassing.
Structure:
Participants:
Component (VisualComponent)defines the interface for objects that can have responsibilities added to them
dynamically.
ConcreteComponent (TextView)
defines an object to which additional responsibilities can be attached.
Decoratormaintains a reference to a Component object and defines an interface that conforms to
Component's interface.
ConcreteDecorator (BorderDecorator, ScrollDecorator)
adds responsibilities to the component.
Collaborations:
Decorator forwards requests to its Component object. It may optionally perform
additional operations before and after forwardingthe request.
Consequences:
The Decorator pattern has at least two key benefits and two liabilities:
1. More flexibility than static inheritance.
2. Avoids feature-laden classes high up in the hierarchy
-
8/11/2019 DP Lab Manual
84/90
Implementation:
Several issues should be considered when applying the Decorator Pattern:
1. Interface conformance
2. Omitting the abstract Decorator class3. Keeping Component classes lightweight.
4. Changing the skin of an object versus changing its guts
Sample Code:
The following code shows how to implement user interface decorators in C++. We'll assume
there's a Component class called VisualComponent.
class VisualComponent {
public:VisualComponent();virtual void Draw();virtual void Resize();// ...};
We define a subclass of VisualComponent called Decorator, which we'll subclass toobtain different decorations.
class Decorator : public VisualComponent {public:
Decorator(VisualComponent*);virtual void Draw();virtual void Resize();// ...private:
VisualComponent* _component;
};
Decorator decorates the VisualComponent referenced by the _component instance
variable, which is initialized in the constructor. For each operation in VisualComponent's
interface, Decorator defines a default implementation that passes the request on to
_component:
void Decorator::Draw () {_component->Draw();}void Decorator::Resize () {_component->Resize();
}
-
8/11/2019 DP Lab Manual
85/90
Subclasses of Decorator define specific decorations. For example, the class
BorderDecorator adds a border to its enclosing component. BorderDecorator is a
subclass of Decorator that overrides the Draw operation to draw the border.
BorderDecorator also defines a private DrawBorder helper operation thatdoes the
drawing. The subclass inherits all other operation implementations from Decorator.
class BorderDecorator : public Decorator {public:BorderDecorator(VisualComponent*, int borderWidth);virtual void Draw();private:void DrawBorder(int);private:int _width;};void BorderDecorator::Draw () {
Decorator::Draw();DrawBorder(_width);}
Known Users:
Many object-oriented user interface toolkits use decorators to add graphical
embellishments to widgets. Examples include InterViews, ET++, and the ObjectWorks\Smalltalk
class library . More exotic applications of Decorator are the DebuggingGlyph from InterViews
and the PassivityWrapper from ParcPlace Smalltalk. A DebuggingGlyph prints out debugging
information before and after it forwards a layout request to its component. This trace informationcan be used to analyze and debug the layout behavior of objects in a complex composition. The
PassivityWrapper can enable or disable user interactions with the component. But the Decoratorpattern is by no means limited to graphical user interfaces, as the following example
the ET++ streaming class illustrates
Related Patterns:
Adapter: A decorator is different from an adapter in that a decorator only changes an object'sresponsibilities, not its interface; an adapter will give an object a completely new interface.
Composite: A decorator can be viewed as a degenerate composite with only one component.
However, a decorator adds additional responsibilitiesit isn't intended for object aggregation
Strategy. A decorator lets you change the skin of an object; a strategy lets you change the guts.These are two alternative ways of changing an object.
Composite
Facade
-
8/11/2019 DP Lab Manual
86/90
-
8/11/2019 DP Lab Manual
87/90
you want to issue a request to one of several objects without specifying the receiver explicitly the set of objects that can handle a request should be specified dynamically
Structure:
A typical object structure might look like this:
Participants:
Handler (HelpHandler)o defines an interface for handling requests.(optional) implements the successor
link. l
ConcreteHandler (PrintButton, PrintDialog)
o handles requests it is responsible for.o can access its successor.o if the ConcreteHandler can handle the request, it does so; otherwise it forwards
the request to its successor.
Cliento initiates the request to a ConcreteHandler object on the chain.
Collaborations:
When a client issues a request, the request propagates along the chain until aConcreteHandler object takes responsibility for handling it.
-
8/11/2019 DP Lab Manual
88/90
Consequences:
Chain of Responsibility has the following benefits and liabilities
Reduced coupling
Added flexibility in assigning responsibilities to objects. Receipt isn't guaranteed.
Implementation:
Here are implementation issues to consider in Chain of Responsibility
1.Implementing the successor chain. There are two possible ways to implement thesuccessor chain:
a. Define new links
b. Use existing links.
2. Connecting successors
3.Representing requests
4.Automatic forwarding in Smalltalk
Sample Code:
The following example illustrates how a chain of responsibility can handle requests for an on-line
help system like the one described earlier. The help request is an explicit operation. We'll useexisting parent references in the widget hierarchy to propagate requests between widgets in the chain,
and we'll define a reference in the Handler class to propagate help requests between nonwidgets inthe chain.
The HelpHandler class defines the interface for handling help requests. It maintains a helptopic (which is empty by default) and keeps a reference to its successor on the chain of help handlers.
The key operation is HandleHelp, which subclasses override. HasHelp is a convenienceoperation for checking whether there is an associated help topic.
typedef int Topic;const Topic NO_HELP_TOPIC = -1;class HelpHandler {public:
HelpHandler(HelpHandler* = 0, Topic = NO_HELP_TOPIC);virtual bool HasHelp();virtual void SetHandler(HelpHandler*, Topic);virtual void HandleHelp();private:HelpHandler* _successor;Topic _topic;};
-
8/11/2019 DP Lab Manual
89/90
HelpHandler::HelpHandler (HelpHandler* h, Topic t) : _successor(h), _topic(t) { }bool HelpHandler::HasHelp () {return _topic != NO_HELP_TOPIC;}void HelpHandler::HandleHelp () {if (_successor != 0) {_successor->HandleHelp();}}
All widgets are subclasses of the Widget abstract class. Widget is a subclass of HelpHandler,since all user interface elements can have help associated with them. (We could have used a mixin-
based implementation just as well.)
class Widget : public HelpHandler {protected:Widget(Widget* parent, Topic t = NO_HELP_TOPIC);private:Widget* _parent;};Widget::Widget (Widget* w, Topic t) : HelpHandler(w, t) {_parent = w;}
We can invoke the help request by calling HandleHelp on any object on the chain. To start the
search at the button object, just call HandleHelp on it:
button->HandleHelp();
Known Users:
Several class libraries use the Chain of Responsibility pattern to handle user events. Theyuse different names for the Handler class, but the idea is the same: When the user clicks the mouse or
presses a key, an event gets generated and passed along the chain. MacApp and ET++ call it"EventHandler," Symantec's TCL library calls it "Bureaucrat," and NeXT's AppKituses the name "Responder
ET++ uses Chain of Responsibility to handle graphical update.
-
8/11/2019 DP Lab Manual
90/90
Related Patterns:
Chain of Responsibility is often applied in conjunction withComposite. There, a
component'sparent can act as its successor.
Command Behavioural Patterns