Object Oriented Programming Systems
Object Oriented Programming Systems
TABLE OF CONTENTS
1. INTRODUCTION .......................................................................................................................................... 3
1.1. COMPUTER PROGRAM .............................................................................................................................. 3
1.2. PROGRAM DESIGN METHODS................................................................................................................... 3
2. CONCEPTS .................................................................................................................................................... 5
2.1. ENCAPSULATION ...................................................................................................................................... 5
2.2. MODIFIERS ............................................................................................................................................... 5
2.3. INHERITANCE ......................................................................................................................................... 12
2.4. POLYMORPHISM ..................................................................................................................................... 14
2.5. INTERFACES ........................................................................................................................................... 15
2.6. PACKAGES .............................................................................................................................................. 17
3. INTRODUCTION TO UNIFIED MODELING LANGUAGE (UML) .................................................. 19
3.1. HISTORY OF THE UML ........................................................................................................................... 19
3.2. BRIEF OVERVIEW OF UML ..................................................................................................................... 19
3.3. CONCEPTUAL MODEL OF UML .............................................................................................................. 20
3.4. DIAGRAMS IN UML 1.5 VERSION .......................................................................................................... 20
3.5. USE CASE DIAGRAMS ............................................................................................................................. 21
3.6. CLASS DIAGRAMS ................................................................................................................................... 23
3.7. PACKAGES AND OBJECT DIAGRAMS ...................................................................................................... 25
3.8. SEQUENCE DIAGRAMS ........................................................................................................................... 27
3.9. COLLABORATION DIAGRAM................................................................................................................... 28
3.10. STATE CHART DIAGRAMS ...................................................................................................................... 29
3.11. ACTIVITY DIAGRAMS ............................................................................................................................. 30
3.12. COMPONENT AND DEPLOYMENT DIAGRAMS ......................................................................................... 32
4. OBJECT ORIENTED PROGRAMMING CONCEPTS ......................................................................... 33
4.1. WHAT IS AN OBJECT?............................................................................................................................. 33
4.2. WHAT IS A CLASS? ................................................................................................................................. 33
4.3. INSTANCE VARIABLES. ........................................................................................................................... 34
4.4. CLASS VARIABLES .................................................................................................................................. 34
4.5. LOCAL VARIABLES ................................................................................................................................. 35
4.6. CREATING METHODS .............................................................................................................................. 35
4.7. VARIABLE SCOPE ................................................................................................................................... 36
4.8. CONSTRUCTOR METHOD........................................................................................................................ 36
4.9. OVERLOADING CONSTRUCTORS............................................................................................................. 36
4.10. METHOD OVERLOADING AND OVERRIDING ........................................................................................... 37
4.11. 'IS A', 'HAS A' RELATIONSHIP ................................................................................................................... 40
4.12. VARIABLES ARE SHADOWED AND METHODS ARE OVERRIDDEN ............................................................. 41
4.13. LATE BINDING ........................................................................................................................................ 41
5. COLLECTIONS .......................................................................................................................................... 42
5.1. WHAT IS A COLLECTIONS FRAMEWORK?............................................................................................... 42
5.2. WHAT ARE THE BENEFITS OF A COLLECTIONS FRAMEWORK? ............................................................... 42
5.3. ARE THERE ANY DRAWBACKS?.............................................................................................................. 43
5.4. INTERFACES ........................................................................................................................................... 43
5.5. GENERICS ............................................................................................................................................... 44
5.6. COLLECTION .......................................................................................................................................... 44
5.7. SET ......................................................................................................................................................... 44
5.8. LIST ........................................................................................................................................................ 44
5.9. MAP ....................................................................................................................................................... 45
5.10. OBJECT ORDERING................................................................................................................................. 45
5.11. GENERAL INFO ....................................................................................................................................... 45
6. PROCESS MODELS ................................................................................................................................... 50
6.1. ITERATIVE AND INCREMENTAL DEVELOPMENT ..................................................................................... 50
6.2. EVOLUTIONARY PROTOTYPING .............................................................................................................. 52
1. Introduction
▪ If, on the other hand, you enter a legal command that does not make any sense in the
current context, it is a semantic error.
• A style of programming in which the programmer divides his program's source code
into logically structured chunks of code.
• This is a design approach where complex systems are broken down into smaller,
more manageable pieces
• A program or program module that has one beginning and one ending, and each step
in the program execution consists of one of the following
Sequence (Executing the sequence of instructions one after the other)
Selection (Presentation of a condition and the choice between two actions.)
Repetition (Presentation of set of instructions to be performed rapidly as long as
Condition is true.)
1. Coupling - The degree to which one class is connected to relies upon other class.
2. Cohesion - The degree to which the attributes and behaviors of a single class are related
Each other.
By striving for high cohesion and low coupling, we want each class to focus on essentially
one thing and for each class to be as independent as possible. The reason behind the goals
of high cohesion and low coupling is object reusability.
2. Concepts
Three basic concepts underlining Object Oriented Programming Concepts
2.1. Encapsulation
When an object carries out its operations, those operations are hidden. This is the essence
of encapsulation.
Encapsulation is a method which enables you to hide inside the object, both the data fields
and the methods that act on that data.
Encapsulation is achieved by using modifiers. Modifiers are language keywords that modify
the definition of a class, method or a variable.
2.2. Modifiers
Modifiers fall into two categories:
Access modifiers: public, protected, private.
Non-access modifiers (including strictfp, final, and abstract).
The fourth access level (default) is what you get when no access modifier is used.
Methods and instance (nonlocal) variables are called members, and members can use all
four access levels: public, protected, default and public
Notice that neither the member variable nor the method supplies an access modifier. So they
take on the default access modifier implicitly.
The superclass (Beverage) is in a different package from the subclass (Tea). The import
statement at the top of the Tea file is trying to import the Beverage class. The Beverage file
compiles fine, but Tea, it will not compile because its superclass, Beverage, has default
access and is in a different package.
Default members can be accessed only by other classes in the same package
Example
If the public class is to be use is in different package from the class you are writing, you still
need to import the public class.
Members
public members can be accessed by all classes, even in different packages
Example
Example
A subclass outside the package cannot access a member through a reference variable.
A protected member is accessible by all classes in the same package and subclasses of
other packages.
For a subclass outside the package, the protected member can be accessed only through
inheritance.
Visibility
Visibility Public Protected Default Private
Abstract modifier
There are situations where you need to define a class which declares the structure of a given
abstraction without providing a complete implementation of every method. You can declare
that certain methods are required to be overridden by subclasses using the abstract type
modifier.
Any class which contains any methods declared abstract must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class keyword at
the beginning of the class declaration. Such classes cannot be directly instantiated with the
new operator since their complete implementation is undefined.
You cannot declare abstract constructors, or abstract static methods. Any subclass of an
abstract class must either implement all of the abstract methods in the super class, or be
itself declared abstract.
Final modifier
Can be considered as a constant. All methods and instance variables may be overridden by
default. If you wish to declare that you want to no longer allow subclasses to override your
variables or methods, you can declare them final.
You should make a final class only if you need an absolute guarantee that none of the
methods in that class will ever be overridden. If you're deeply dependent on the
implementations of certain methods, then using final gives you the security that nobody can
change the implementation.
You'll notice many classes in the Java core libraries are final. For example, the String class
cannot be subclassed.
You can't mark a class as both abstract and final. They have nearly opposite meanings. An
abstract class must be subclassed, whereas a final class must not be subclassed.
Synchronized modifier
• A synchronized keyword indicates that a method can be accessed by only one thread
at a time.
• synchronized modifier applies only to methods
• synchronized methods can have any access control and can also be marked final
• synchronized methods cannot be abstract
Static modifier
• The static modifier specifies that a variable or method is the same for all objects of a
particular class. When a variable is declared as being static, it is only allocated once
regardless of how many objects are instantiated. (Typically new variables are
allocated for each instance of a class)
• All instantiated objects share the same instances of the static variable. When you
declare a method static, it is not instantiated with each object, but is part of the entire
class. Therefore you invoke the method by preceding it with the class name.
• If a method behavior is not dependent on the instance variable values of the object
and is to behave is the same manner always the method is marked static.
• An instance of a class does not need to exist in order to use a static member of a
class.
• There is only one copy of the static variable per class and all instances share it.
Example
Class Modifiers
Modifier Meaning
Public Accessible from all other classes
Abstract Class cannot be instantiated
Final No sub classes can be created
Constructor Modifiers
Modifier Meaning
public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class
Field Modifiers
Modifier Meaning
public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class
Static Only a Single value for all instances
Transient It is not part of the persistent state of an object
Final It is a Constant
Method Modifiers
Modifier Meaning
Public Accessible from all classes
Protected Accessible only from within and all sub classes
private Accessible only from within its own class
Static Bound to class itself, not to any instance
Final No subclass can override it.
Native Implemented in another programming language
synchronised Must be locked before a thread can invoke it.
Abstract No method Body, extended class should implement it
2.3. Inheritance
2.3.1. Super class and Subclass
Using inheritance you can create a general class that trait comments to related items. This
class then can be inherited by the other more specific classes each adding things unique to
it.
A class that is inherited is called a super class. The class that does the inheritance is called
the subclass. Therefore a subclass is a specialized version of a super class. It inherits all of
the instance variables and methods defined by the super class, and add its own unique
elements.
E.g.
Specialized
Example
2.4. Polymorphism
Combines Greek Words Poly, Morphism. Poly: Many and Morphism: Forms.
The quality of having more than one form. In the context of Object Oriented Programming,
polymorphism refers to the fact a single operation can have different behavior in different
objects.
2.5. Interfaces
2.5.1. What Is an Interface?
An interface defines a protocol of behavior that can be implemented by any class anywhere
in the class hierarchy. An interface defines a set of methods but does not implement them. A
class that implements the interface agrees to implement all the methods defined in the
interface, thereby agreeing to certain behavior.
Because an interface is simply a list of unimplemented, and therefore abstract, methods, you
might wonder how an interface differs from an abstract class. The differences are significant.
Suppose that you have written a class that can watch stock prices coming over a data feed.
This class allows other classes to register to be notified when the value of a particular stock
changes. First, the class, which we'll call StockMonitor, would implement a method that
lets other objects register for notification:
The watchStock method ensures, through the data type of its first argument, that all
registered objects implement the valueChanged method. It makes sense to use an
interface data type here because it matters only that registrants implement a particular
method. If StockMonitor had used a class name as the data type, which would artificially
force a class relationship on its users. Because a class can have only one superclass, it
would also limit what type of objects can use this service.
This interface defines three constants, which are the ticker symbols of watchable stocks. This
interface also declares, but does not implement, the valueChanged method. Classes that
implement this interface provide the implementation for that method.
Member declarations in an interface disallow the use of some declaration modifiers; you
cannot use transient, volatile, or synchronized in a member declaration in an
interface. Also, you may not use the private and protected specifiers when declaring
members of an interface.
When a class implements an interface, it is essentially signing a contract. Either the class
must implement all the methods declared in the interface and its superinterfaces, or the class
must be declared abstract. The method signature--the name and the number and type of
arguments in the class--must match the method signature as it appears in the interface. The
StockApplet implements the StockWatcher interface, so the applet provides an
implementation for the valueChanged method. The method ostensibly updates the applets
display or otherwise uses this information.
2.6. Packages
Java provides a large number of classes. A package organizes there classes into groups.
The lang package is one of the most important packages in Java. All classes in this package
can be used in your program with out explicit importing.
Now you can refer to the Circle class by its simple name:
This approach works well if you use just a few members from the graphics package. But if
you use many classes and interfaces from a package, you can import the entire package.
import graphics.*;
Now you can refer to any class or interface in the graphics package by its short name:
The asterisk in the import statement can be used only to specify all the classes within a
package, as shown here. It cannot be used to match a subset of the classes in a package.
For example, the following does not match all the classes in the graphics package that
begin with A:
Instead, it generates a compiler error. With the import statement, you can import only a
single package member or an entire package.
For your convenience, the Java runtime system automatically imports three entire packages:
The use of different notations brought confusion to the market since one symbol meant
different things to different people. To resolve this confusion Unified Modeling Language
(UML) was introduced.
“UML is a language used to specify, visualize, and document the artifacts of an object-
oriented system under development. It represents the unification of the Booch, OMT, and
Objector notations, as well as the best ideas from a number of other methodologies”.
UML is an attempt to standardize the artifacts of analysis and design: semantic models,
syntactic notation, and diagrams.
In November 1997, the UML was adopted as the standard modeling language by the
Object Management Group (OMG).
The UML is only a language and so is just one part of a software development method.
The UML is process independent, although optimally it should be used in a process that is
use case driven, architecture-centric, iterative, and incremental.
It is a graphical language and has graphical symbols. Each symbol has well defined
semantics
1. Things
2. Relationships
3. Diagrams
Things are the abstractions that are first-class citizens in a model; relationships tie these
things together; diagrams group interesting collections of things.
• A Class Diagram shows a set of classes, interfaces, and collaborations and their
relationships.
• An Object Diagram shows a set of objects and their relationships.
• A Use Case Diagram shows a set of use cases and actors (a special kind of class)
and their relationships.
• Both Sequence Diagrams and Collaboration Diagrams are kinds of Interaction
Diagrams.
• A Statechart Diagram shows a state machine, consisting of states, transitions,
events, and activities. Statechart diagrams address the dynamic view of a system.
• An Activity Diagram is a special kind of a statechart diagram that shows the flow
from activity to activity within a system.
• A Component Diagram shows the organization and dependencies among a set of
components. These diagrams address the static implementation view of a system.
• A Deployment Diagram shows the configuration of run-time processing nodes and
the components that live on them. These diagrams address the static deployment
view of architecture.
Use Case diagrams show the interactions between use cases and actors. Use cases
represent system functionality, the requirements of the system from the user's perspective.
That is, the actions that the system performs to generate results requested by the actor of
the system.
Actors represent the people or systems that provide or receive information from the system;
they are among the stakeholders of a system. That is they can be either “External entities
that interact with the system” or “A role that a user plays with respect to the system”.
Use Case diagrams, therefore, show which actors initiate use cases; they also illustrate that
an actor receives information from a use case. In essence, a Use Case diagram can illustrate
the requirements of the system.
Notations
Actor UseCase
Transfer Funds
Customer
Deposit Funds
The above Use Case diagram shows the interactions between the use cases and actors of
an ATM system. In this example, the bank's customer initiates a number of use cases:
Withdraw Money, Deposit Funds, Transfer Funds, Make Payment, View Balance, and
Change PIN. A few of the relationships are worthy of further mention. The bank officer can
also initiate the Change PIN use case. The Make Payment use case shows an arrow going
to the credit system. External systems may be actors and, in this case, the credit system is
shown as an actor because it is external to the ATM system. The arrow going from a use
case to an actor illustrates that the use case produces some information that an actor uses.
In this case, the Make Payment use case provides credit card payment information to the
credit system.
Much information can be gleaned from viewing Use Case diagrams. This one diagram shows
the overall functionality of the system. Users, project managers, analysts, developers, quality
assurance engineers, and anyone else interested in the system as a whole can view these
diagrams and understand what the system is supposed to accomplish.
An online retails company wishes to implement a Web-based marketing system with facilities
to aid their purchasing and stock control. The outline requirements for the systems are as
follows:
All customers must be registered with the system. There should be a screen that allows them
to do this on a fill-in-the-form basis. If they fill in all the details required and a valid e-mail
address they will be issued with a customer registration number. Registered customers may
purchase online. Typically they will browse through details of the goods available and select
one or more items. If an item is out of stock it will not be displayed whilst a customer is
browsing. When they have selected all the items they require they can then move to a screen
which enables them to enter their customer number and complete the purchase. Once
ordered, goods are sent to a customer by a dispatcher. Every morning the dispatcher
requests a list of goods that are to be sent out. The list contains the names and addresses of
all the customers who have made an order on the previous day and the items they have
ordered. A buyer determines the range of items that are for sale. A buyer can add new items
to the online catalogue and discontinue the sale of existing items. Each morning the buyer
requests the list of those items for which the quantity in stock is lower than their re-order
level. Items on the list are re-ordered. When new stocks arrive they are received by a
warehouseman who records the new stock levels on the computer system.
a) Draw a use case diagram for this system.
b) Develop a use case description of the way a customer orders goods. Your answer should
show a normal sequence and also list some alternate sequences.
Class diagrams are the most important model in UML that illustrates the structure of the
system. They represent the static view of the system. Class diagrams show the interactions
between classes in the system. Classes can be seen as the blueprint for objects, as we'll
discuss later. An account, for example, is an object. An account is a blueprint for checking
account of a customer therefore an account is a class. Classes contain information and
behavior that acts on that information. The Account class contains the customer's PIN and
behavior to check the PIN. A class on a Class diagram is created for each type of object in a
Sequence or Collaboration diagram. The following are the notations for representing a class
in UML:
Notation Example
Operations Add_student
Delete_student
The Class diagram for the system's Withdraw Money use case is illustrated below:
The Class diagram above shows the relationships between the classes that implement the
Withdraw Money use case. This is done with four classes: Card Reader, Account, ATM
Screen, and Cash Dispenser. Each class on a Class diagram is represented by a rectangle
divided into three sections. The first section shows the class name. The second section
shows the attributes the class contains. An attribute is a piece of information that is
associated with a class. For example, the Account class contains three attributes: Account
Number, PIN, and Balance. The last section contains the operations of the class. An
operation is some behavior that the class will provide. The Account class contains four
operations: Open, Withdraw Funds, Deduct Funds, and Verify Funds.
The lines connecting classes show the communication relationships between the classes.
For instance, the Account class is connected with the ATM Screen class because the two
directly communicate with each other. The Card Reader is not connected to the Cash
Dispenser because the two do not communicate.
Developers use Class diagrams to actually develop the classes. Tools such as Rose
generate skeletal code for classes, and then developers flesh out the details in the language
of their choice. Analysts use Class diagrams to show the details of the system. Architects
also look at Class diagrams to see the design of the system. If one class contains too much
functionality, an architect can see this in the Class diagram and split out the functionality into
multiple classes. Should no relationship exist between classes that communicate with each
other, an architect or developer can see this too. Class diagrams should be created to show
the classes that work together in each use case, and comprehensive diagrams containing
whole systems or subsystems can be created as well.
Packages appear as rectangles with small tabs at the top. The package name is on the tab
or inside the rectangle. The dotted arrows are dependencies. One package depends on
another if changes in the other could possibly force changes in the first.
Object diagrams show instances instead of classes. They are useful for explaining small
pieces with complicated relationships, especially recursive relationships.
This small class diagram shows that a university Department can contain lots of other
Departments.
The object diagram below instantiates the class diagram, replacing it by a concrete example.
Each rectangle in the object diagram corresponds to a single instance. Instance names are
underlined in UML diagrams. Class or instance names may be omitted from object diagrams
as long as the diagram meaning is still clear.
3. Initialize Screen
4. Open Account
5. Prompt for Pin
11.Enter Amount
12. Withdraw Fund
13. Verify Fund
14.Deduct Funds
This Sequence diagram shows the flow of processing through the Withdraw Money use
case. Any actors involved are shown at the top of the diagram; the customer actor is shown
in the above example. The objects that the system needs in order to perform the Withdraw
Money use case are also shown at the top of the diagram. Each arrow represents a message
passed between actor and object or object and object to perform the needed functionality.
One other note about Sequence diagrams is that they display objects, not classes. Classes
represent types of objects; Objects are specific that is instead of just customer the Sequence
diagram can show John (Customer Name).
The use case starts with the customer inserting his card into the card reader, an object
indicated by the rectangle at the top of the diagram. Then, the card reader reads the card
number, opens the account object, and initializes the ATM screen. The screen prompts
customer for PIN. Customer enters the Pin. The screen verifies the PIN with the account
object and they match. The screen presents customer with the options, and customer
chooses withdraw. The screen then prompts the customer for the amount to withdraw.
Customer enters amount. Then, the screen withdraws the funds from the account. This
initiates a series of processes that the account object performs. First, customer’s account
verifies that the account contains at least the requested amount. Then, it deducts the funds
from the account. Next, it instructs the cash dispenser to provide the required amount in
cash. Customer’s account also instructs the dispenser to provide a receipt. Lastly, it instructs
the card reader to eject the card.
This Sequence diagram illustrated the entire flow of processing for the Withdraw Money use
case by showing a specific example of customer withdrawing cash from the account. Users
can look at these diagrams to see the specifics of their business processing. Analysts see
the flow of processing in the Sequence diagrams.
Developers see objects that need to be developed and operations for those objects. Quality
assurance engineers can see the details of the process and develop test cases based on the
processing. Sequence diagrams are therefore useful for all stakeholders in the project.
6: Enter Pin
9: Select Transaction(Withdraw) 7: Verify Pin
11: Enter Amount 12: Withdraw Fund
ATM Account
Screen
5: Prompt for Pin
: Customer 8: Prompt for Transaction
10: Prompt for Amount
15: Provide Cash
16: Provide Receipt
4: Open Account
3: Initialize Screen
1: AcceptCard
Cash
17: Eject Card Dispenser
2: ReadCardNo.
CardReader
28 Diploma – Object Oriented Programming
[Type text]
Accredited Course Provider
In this Collaboration diagram, the objects are represented as rectangles and the actors are
stick figures, as before. Whereas the Sequence diagram illustrates the objects and actor
interactions over time, the Collaboration diagram shows the objects and actor interactions
without reference to time. For example, in this diagram, we see that the card reader instructs
customer's account to open and customer’s account instructs the card reader to eject the
card. Also, objects that directly communicate with each other are shown with lines drawn
between them. If the ATM screen and cash dispenser directly communicated with one
another, a line would be drawn between them. The absence of a line means that no
communication occurs directly between those two objects.
Collaboration diagrams, therefore, show the same information as Sequence diagrams, but
people look at Collaboration diagrams for different reasons. Quality assurance engineers and
system architects look at these to see the distribution of processing between objects.
Suppose that the Collaboration diagram was shaped like a star, with several objects
communicating with a central object. A system architect may conclude that the system is too
dependent on the central object and redesign the objects to distribute the processing power
more evenly. This type of interaction would have been difficult to see in a Sequence diagram.
Open
OverDrawn
Do: Send Notice To Customer
Deposit( Balance < 0 )
Customer Request Closure
Closed
Check Balance( Balance < 0 for > 30 Days )
In this diagram, we can see the states in which an account can exist. We can also see how
an account moves from one state to another. For example, when an account is open and the
customer requests the account's closure, the account moves to the closed state. The
customer's request is called the event and the event is what causes a transition from one
state to another.
If the account is open and the customer makes a withdrawal, the account may move to the
overdrawn state. This will only happen if the balance of the account is less than zero. We
show this by placing [Balance < 0] on the diagram. A condition enclosed in square brackets
is called a guard condition, and controls when a transition can or cannot occur.
There are two special states that is the start state and the stop state. The start state is
represented by a black dot on the diagram, and indicates what state the object is in when it is
first created. The stop state is represented by a bull’s-eye, and shows what state the object is
in just before it is destroyed. On a Statechart diagram, there is one and only one start state.
On the other hand, you can have no stop state, or there can be as many stop states as you
need.
Certain things may happen when the object is inside a particular state. In our example, when
an account is overdrawn, a notice is sent to the customer. Processes that occur while an
object is in a certain state are called actions.
Statechart diagrams aren't created for every class; they are used only for very complex
classes. If an object of the class can exist in several states, and behaves very differently in
each of the states, you may want to create a Statechart diagram for it. Many projects won't
need these diagrams at all. If they are created, developers will use them when developing
the classes.
Statechart diagrams are created for documentation only. For Example: When you generate
code from your Rational Rose model, no code will be generated from the information on the
Statechart diagrams.
The activity diagram may be divided into vertical swimlanes. Each swimlane represents a
different role within the workflow. By looking at the activities within a given swimlane, you can
find out the responsibility of that role. By looking at the transitions between activities in
different swimlanes, you can find out who needs to communicate with whom. All of this is
very valuable information when trying to model or understand the business process. Activity
diagrams do not need to be created for every workflow, but they are powerful communication
tools, especially with large and complex workflows.
A transition may branch into two or more mutually exclusive transitions. Guard expressions
(inside [ ]) label the transitions coming out of a branch. A branch and its subsequent merge
marking the end of the branch appear in the diagram as hollow diamonds.
A transition may fork into two or more parallel activities. The fork and the subsequent join of
the threads coming out of the fork appear in the diagram as solid bars.
Collect Customer
Information
[ Meets Criteria ]
[ Doesn't Meet Criteria ]
Review Credit History
Open Account
Sign Paperwork
Issue Pass
Book
When drawing physical diagrams both the deployment and the component diagrams are
combined into one physical diagram.
The deployment diagram contains nodes and connections where a node usually represents a
piece of hardware in the system and a connection depicts the communication path used by
the hardware to communicate which usually indicates a method such as TCP/IP.
The component diagram contains components and dependencies where components
represent the physical packaging of a module of code and the dependencies between
components show how changes made to one component may affect the other components in
the system.
Component diagrams can also show the interfaces used by the components to communicate
with each other.
Notations Example
Component
Node Registration Server
All objects with the same attributes and behaviors belongs to the same class.
Practical Example of a class
Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and the methods within that object. A software object that modeled your real-world
bicycle would have variables that indicated the bicycle's current state: Its speed is 18 mph, its
pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables are formally
known as instance variables because they contain the state for a particular bicycle object,
and in object-oriented terminology, a particular object is called an instance. The above figure
illustrates a bicycle modeled as a software object.
Example
The return type is the primitive type or class of the value returned by the method. It can be of
the primitive type, a class name or void if the method does not return a value at all.
Void displayName() – no return type
Int calucualteSum() – returns a int value
Methods parameter list is a set of variable declarations, separated by commas inside
parenthesis. These parameters become local variables in the body of the method.
Example
class Camera
{
Void clickButton()
{
// this method does not take any arguments
// returns no value
}
int CountPhotographs() {
//no arguments
//return int value
}
boolean changeShutterSpped(int noofMiiliSeconds) {
// this method takes a parameter int data type
// returns a Boolean variable true/false
}
}
A variable with a local scope, can be used only inside the block in which it was defined.
Instance variables have a scope that extends to the entire class, so they can be used by any
of the instance methods with in that class.
//constructor definition
twoDPoint(){
x= y = 0;
}
}
No argument Constructor
this keyword is used to refer to the current object. It can be used to,
▪ refer to the current objects member variables,
▪ refer to current objects methods
▪ pass a reference to the current object to a method
▪ return a reference current object
super(x,y);
super(x,y);
super.m(); Invokes super class Constructor
with x and y arguments
super.m();
Calls the super class method
called m()
The methods are said to be overloaded and the process is related to as ‘method
overloading’. When an overloaded method is involved, java uses the type and or numbers of
arguments as its guide to determine which version of the overloaded method to actually call.
Thus overloaded methods should differ in type and/or number of their parameters. Difference
in argument type alone is insufficient.
• If two (or more) methods of a class (whether both declared in the same class, or both
inherited by a class, or one declared and one inherited) have the same name but
different signatures, then the method name is said to be overloaded.
• The signature of a method consists of the name of the method and the number and
types of formal parameters in particular order. A class must not declare two methods
with the same signature, or a compile-time error occurs.
• Only the method name is reused in overloading, so method overloading is actually
method name overloading.
• Overloaded methods may have arguments with different types and order of the
arguments may be different.
• Overloaded methods are not required to have the same return type or the list of
thrown exceptions.
• Overloading is particularly used while implementing several methods that implement
similar behavior but for different data types.
• Overloaded methods are independent methods of a class and can call each other just
like any other method.
• Constructors can also be overloaded in similar fashion, as they are also methods.
• Java has some classes with overloaded constructors. For example, wrapper class for
int has two overloaded constructors. One constructor takes int as argument and
another takes string argument.
• Integer aNumber = new Integer(2);
• Integer anotherNumber = new Integer("2005");
• One constructor can call another overloaded constructor of the same class by using
this keyword.
• One constructor can call constructor of its super class by using the super keyword. ]
• When a class defines a method with same method name, argument types, argument
order and return type as a method in its super class, its called method overriding.
• The method in the super class is said to be overridden by the method in the subclass.
• Overriding method actually replaces the behavior in super class for a subclass.
• Methods overriding cannot be declared more private than the super class method.
• Any exceptions declared in overriding method must be of the same type as those
thrown by the super class, or a subclass of that type.
• Methods declared as final cannot be overridden.
• An overriding method can be declared as final as the keyword final only suggests that
this method cannot be further overridden.
• Methods declared as private cannot be overridden as they are not visible outside the
class.
• Overriding method can call the overridden method (just like any other method) in its
super class with keyword super.
• The call super.method() will invoke the method of immediate super class.
• Though keyword super is used to refer super class, method call
Generalization is the result of abstracting the common attributes and behavior from a group
of closely related classes and moving them into a common super class. Specialization is the
inverse of generalization.
A common test for generalization is the IS-A test. Generalization may also look for following
phrases in problem definition to identify the inheritance.
• "is a"
• "is a type of"
• "is a kind of"
For example, if part of problem definition says 'Dog IS AN animal', implementation will more
likely have Animal class and Dog class will be the subclass of the Animal class.
When a class member variable is accessed through an object reference, the variable to be
selected depends on the declared class of the object reference variable.
However, when a method is called on through an object reference, the actual method
invoked depends on the type of an object reference.
A subclass can have a variable with the same name as a variable in the parent class. This is
called as shadowing the parent class variable. It is not overriding of variable.
5. Collections
A collection (sometimes called a container) is simply an object that groups multiple elements
into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit
data from one method to another. Collections typically represent data items that form a
natural group, like a poker hand (a collection of cards), a mail folder (a collection of letters),
or a telephone directory (a collection of name-to-phone-number mappings).
If you've used Java -- or just about any other programming language -- you're already familiar
with collections. Collection implementations in earlier versions of Java included Vector,
Hashtable, and array. While earlier versions of Java contained collection implementations,
they did not contain a collections framework.
The best known examples of collections frameworks are the C++ Standard Template Library
(STL), and Smalltalk's collection classes.
collections sub-APIs, so you had to learn each one from scratch and it was easy to
make mistakes when using them. With the advent of standard collections interfaces,
the problem goes away.
• It reduces effort to design new APIs: This is the flip-side of the previous advantage:
designers and implementers don't have to reinvent the wheel each time they create an
API that relies on collections. They just use the standard collections interfaces.
• It fosters software reuse: New data structures that conform to the standard collection
interfaces are by nature reusable. The same goes for new algorithms that operate on
objects that implement these interfaces.
5.4. Interfaces
The core collection interfaces are the interfaces used to manipulate collections, and to pass
them from one method to another. The basic purpose of these interfaces is to allow
collections to be manipulated independently of the details of their representation. The core
collection interfaces are the heart and soul of the collections framework. When you
understand how to use these interfaces, you know most of what there is to know about the
framework. The core collections interfaces are shown below:
The core collection interfaces form a hierarchy: a Set is a special kind of Collection, and a
SortedSet is a special kind of Set, and so forth. Note also that the hierarchy consists of two
distinct trees: a Map is not a true Collection.
To keep the number of core collection interfaces manageable, the JDK doesn't provide
separate interfaces for each variant of each collection type. (Among the possible variants are
immutable, fixed-size, and append-only.) Instead, the modification operations in each
interface are designated optional: a given implementation may not support some of these
operations. If an unsupported operation is invoked, a collection throws an
UnsupportedOperationException. Implementations are responsible for documenting which
of the optional operations they support. All of the JDK's general purpose implementations
support all of the optional operations.
The four sections that follow teach you how to use each of the four basic core collection
interfaces. In particular, they describe the idioms that allow you to use these interfaces
effectively.
5.5. Generics
When you take an element out of a Collection, you must cast it to the type of element that is
stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not
check that your cast is the same as the collection's type, so the cast can fail at run time.
Generics provides a way for you to communicate the type of a collection to the compiler, so
that it can be checked. Once the compiler knows the element type of the collection, the
compiler can check that you have used the collection consistently and can insert the correct
casts on values being taken out of the collection.
5.6. Collection
The Collection interface is the root of the collection hierarchy. A Collection represents a
group of objects, known as its elements. Some Collection implementations allow duplicate
elements and others do not. Some are ordered and others unordered. The JDK doesn't
provide any direct implementations of this interface: It provides implementations of more
specific subinterfaces like Set and List. This interface is the least common denominator that
all collections implement. Collection is used to pass collections around and manipulate them
when maximum generality is desired.
5.7. Set
A Set is a collection that cannot contain duplicate elements. As you might expect, this
interface models the mathematical set abstraction. It is used to represent sets like the cards
comprising a poker hand, the courses making up a student's schedule, or the processes
running on a machine.
5.8. List
A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate
elements. The user of a List generally has precise control over where in the List each
element is inserted. The user can access elements by their integer index (position). If you've
used Vector, you're already familiar with the general flavor of List.
5.9. Map
A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key
can map to at most one value. If you've used Hashtable, you're already familiar with the
general flavor of Map.
The last two core collection interfaces ( SortedSet and SortedMap) are merely sorted
versions of Set and Map. In order to understand these interfaces, you have to know how
order is maintained among objects. Even if you don't plan to use SortedSet or SortedMap,
read the following section if you plan to sort Lists.
5.10.1. SortedSet
A SortedSet is a Set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. The SortedSet interface is used
for things like word lists and membership rolls.
5.10.2. SortedMap
A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and
telephone directories.
5.11.1. Set
• A group of objects with no duplication
• SortedSet -- subinterface of Set
• TreeSet -- sorted
• HashSet-- best performance, unordered.
• LinkedHashSet-- since jdk 1.4
5.11.2. List
• A subinterface of Collection
• A group of objects with duplicate elements
• ArrayList -- like Vector, but its methods are not synchronized.
• LinkedList -- quick sequential access.
5.11.3. Vector
• Has been retrofitted to implement List interface.
• Provides methods for working with dynamic arrays of varied element types.
• Its methods are synchronized.
• Slower access.
5.11.5. Map
• Maps keys and values.
• Hashtable -- historical implementation.
• SortedMap
• HashMap
• TreeMap
• LinkedHashMap
• IdentityHashMap
• WeakHashMap
Example Vector
import java.lang.Integer;
import java.util.Enumeration;
import java.util.Vector;
class VectorEx
{
public static void main(String args[])
{
Vector v=new Vector(10,10);
for (int i=0;i<20;i++)
{
v.addElement(new Integer(i)); //adding an integer object
}
System.out.println("Vector in original order using an Enumeration");
for (Enumeration e=v.elements();e.hasMoreElements();)
{
System.out.print(e.nextElement()+" ");
}
System.out.println();
System.out.println();
System.out.println("\nVector as a String");
System.out.println(v.toString());
}
}
Example HashSet
import java.util.*;
class HashSetEx
{
public static void main(String args[])
{
HashSet h = new HashSet();
h.add("b");
h.add("z");
h.add("x");
h.add("g");
h.add("442");
h.add("222");
h.add("3232");
System.out.println("the hash set is");
System.out.println(h+"\n");
System.out.println("the size of hash set is "+h.size());
}
}
Example TreeSet
import java.util.*;
class TreeSetEx
{
public static void main(String args[])
{
TreeSet t=new TreeSet();
t.add("a");
t.add("d");
t.add("c");
t.add("b");
System.out.println(" the tree set is as follows");
System.out.println(t +"\n");
t.remove("c");
System.out.println("after removing the elements 3 is as follows :");
System.out.println(t +"\n");
t.add("5");
t.add("4");
t.add("7");
System.out.println("after adding more element s is as follows:");
System.out.println(t +"\n");
System.out.println("the part of the tree set upto the element is as
follows:");
System.out.println(t.headSet("b"));
System.out.println(" the part of the tree set from the element is as
follows:");
System.out.println(t.tailSet("b"));
}
}
48 Diploma – Object Oriented Programming
[Type text]
Accredited Course Provider
Example LinkList
import java.util.*;
class LisnkListEx
{
public static void main(String args[])
{
LinkedList l=new LinkedList();
l.add("NCC");
l.add("BIT");
l.add("BCS");
l.add("ACS");
System.out.println("the linked List after adding the first 3 elements is as
follows :\n"+l+"\n");
l.addFirst("before BIT");
l.addLast("before ACS ");
System.out.println("the linked List after adding two more elements is as
follows :\n"+l+"\n");
System.out.println("the location of element in the linked list :"+l.get(2)+"\n");
l.remove("ACS");
System.out.println("the linked list after removing the element 'ACS' is as
follows :\n"+l+"\n");
l.set(3,"SCJP");
System.out.println("the linked list after changing the fourth is as follows
:\n"+l+"\n");
}
}
Example - ArrayList
6. Process Models
• They identify which of the services are the most important and which are least
important to them.
• A number of delivery increments are then defined with each increment providing a
subset of the system functionality.
• The allocation of services to increments are then defined with each increment
depends on the service priority.
• Once the system increments have been identified the requirements for the service to
be delivered in the first increment are defined in detail and developed the most
appropriate development process.
• During the development further requirement analysis, for later increment can take
place, but charges for the current increment cannot be accessed.
• Once an increment is completed and delivered, part of the system will be functional,
then the new increments are completed. They are integrated with existing increment
so the system functionality improves with each delivered increment.
Advantages
Disadvantages
Concurr ent
activities
Initial
Specification
version
Outline Intermediate
Development
description versions
Final
Validation
version
Advantages
Disadvantages
Characteristics
Architecture Centric
The Unified Process insists that architecture sit at the heart of the project team's efforts to
shape the system. Since no single model is sufficient to cover all aspects of a system, the
Unified Process supports multiple architectural models and views.
One of the most important deliverables of the process is the executable architecture baseline
which is created during the Elaboration phase. This partial implementation of the system
serves to validate the architecture and act as a foundation for remaining development.
Risk Focused
The Unified Process requires the project team to focus on addressing the most critical risks
early in the project life cycle. The deliverables of each iteration, especially in the Elaboration
phase, must be selected in order to ensure that the greatest risks are addressed first.
Project Lifecycle
Profile of a typical project showing the relative sizes of the four phases. The Unified Process
divides the project into four phases:
1. Inception
2. Elaboration
3. Construction
4. Transition
Inception Phase
Inception is the smallest phase in the project, and ideally it should be quite short. If the
Inception Phase is long then it is usually an indication of excessive up-front specification,
which is contrary to the spirit of the Unified Process.
The following are typical goals for the Inception phase.
1. Establish a justification or business case for the project
2. Establish the project scope and boundary conditions
3. Outline the Use Cases and key requirements that will drive the design tradeoffs
4. Outline one or more candidate architectures
5. Identify risks
6. Prepare a preliminary project schedule and cost estimate
The Lifecycle Objective Milestone marks the end of the Inception phase.
Elaboration Phase
During the Elaboration phase the project team is expected to capture a healthy majority of
the system requirements. However, the primary goals of Elaboration are to address known
risk factors and to establish and validate the system architecture.
The architecture is validated primarily through the implementation of an Executable
Architecture Baseline. This is a partial implementation of the system which includes the core,
most architecturally significant, components. It is built in a series of small, time boxed
iterations. By the end of the Elaboration phase the system architecture must have stabilized
and the executable architecture baseline must demonstrate that the architecture will support
the key system functionality and exhibit the right behavior in terms of performance, scalability
and cost.
The final Elaboration phase deliverable is a plan (including cost and schedule estimates) for
the Construction phase. At this point the plan should be accurate and credible since it should
based on the Elaboration phase experience and since significant risk factors should have
been addressed during the Elaboration phase.
The Lifecycle Architecture Milestone marks the end of the Elaboration phase.
Construction Phase
Construction is the largest phase in the project. In this phase the remainder of the system is
built on the foundation laid in Elaboration. System features are implemented in a series of
short, time boxed iterations. Each iteration results in an executable release of the software.
The Initial Operational Capability Milestone marks the end of the Construction phase.
Transition Phase
The final project phase is Transition. In this phase the system is deployed to the target users.
Feedback received from an initial release (or initial releases) may result in further
refinements to be incorporated over the course of several Transition phase iterations. The
Transition phase also includes system conversions and user training.
The Product Release Milestone marks the end of the Transition phase.
The RUP is not a single concrete prescriptive process, but rather an adaptable process
framework. It is intended to be tailored, in the sense that development organizations and
software project teams will select the elements of the process that are appropriate for their
needs.
The Rational Unified Process (RUP) is also a software process product, originally developed
by Rational Software, and now available from IBM. The product includes a hyperlinked
knowledge base with sample artifacts and detailed descriptions for many different types of
activities. RUP is included in the IBM Rational Method Composer (RMC) product which
allows customization of the process.
• Risks are attacked early in development since each iteration gives the opportunity for
more risks to be identified.
• Software architecture is improved by repeated scrutiny.
Using iterations, a project will have one overall phase plan, but multiple iteration plans.
Involvement from stakeholders is often encouraged at each milestone. In this manner,
milestones serve as a means to obtain stakeholder buy in while providing a constant
measure against requirements and organizational readiness for the pending launch.
Manage requirements
Requirements Management in RUP is concerned with meeting the needs of end users by
identifying and specifying what they need and identifying when those needs change. Its
benefits include the following:
• The correct requirements generate the correct product; the customer's needs are
met.
• Necessary features will be included, reducing post-development cost.
RUP suggests that the management of requirements has the following activities:
• Analyze the problem - is about agreeing on the problem and creating the measures
that will prove its value to the organization.
• Understand stakeholder needs - is about sharing the problem and value with key
stakeholders and finding out what their needs are surrounding the solution idea.
• Define the system - is about creating features from needs and outlining use cases,
activities which show nicely the high-level requirements and the overall usage model
of the system.
• Manage the scope of the system - is about modifying the scope of what you will
deliver based on results so far and selecting the order in which to attack the use-case
flows.
• Refine the system definition - is about detailing use-case flows with the
stakeholders in order to create a detailed Software Requirements Specification (SRS)
that can serve as the contract between your team and your client and that can drive
design and test activities.
• Manage changing requirements - is about how to handle incoming requirement
changes once the project has begun.
Use component-based architecture
Component-based architecture creates a system that is easily extensible, intuitively
understandable and promotes software reuse. A component often relates to a set of objects
in object-oriented programming.
Software architecture is increasing in importance as systems are becoming larger and more
complex. RUP focuses on producing the basic architecture in early iterations. This
architecture then becomes a prototype in the initial development cycle. The architecture
evolves with each iteration to become the final system architecture. RUP also asserts design
rules and constraints to capture architectural rules. By developing iteratively it is possible to
gradually identify components which can then be developed, bought or reused. These
components are often assembled within existing infrastructures such as CORBA and COM,
or Java EE.
information technology. A model in this context is visualization and at the same time a
simplification of a complex designs. RUP specifies which models are necessary and why.
The Unified Modeling Language (UML) can be used for modeling Use-Cases, Class
diagrams and other objects. RUP also discusses other ways to build models.
Quality assessment is the most common failing point of all software projects, since it is often
an afterthought and sometimes even handled by a different team. RUP assists in planning
quality control and assessment by building it into the entire process and involving all
members of a team. No worker is specifically assigned to quality; RUP assumed that each
member of the team is responsible for quality during the entire process. The process focuses
on meeting the expected level of quality and provides test workflows to measure this level.
• The Rational Unified Process is an iterative process. Built into the iterative
approach is the flexibility to accommodate new requirements or tactical
changes in business objectives.
• Models used in RUP, especially those specified using the UML, provide
semantically rich representations of the software systems under development. This
allows the system to easily understood and expressed.
• The rationale behind the rational unified process’s focus on models rather than
paper documents is to minimize the overhead associated with generating and
maintaining documents and to minimize the relevant information content.
• Development under Rational Unified Process is architecture centric. The process
focus on the early development and baseline of a software architecture (component
based).
• Development under Rational Unified Process is use case driven. The Rational
Unified Process places strong emphasis on building systems based on a thorough
understanding of how the delivered system will be used.
• The notions of use cases and scenarios are used to align the process flow from
requirement capture through testing and to provide traceable threads through
development to the delivered system.
• The Rational Unified Process supports object oriented techniques. Each model
is object oriented. Rational Unified Process models are based on the concepts of
objects and classes and the relationships among them and they use the UML as its
notation
• The Rational Unified Process is a configurable process. Although no single
process suitable for all software development organizations, The Rational Unified
Process is tailor able and can be scaled to fit the needs of projects ranging from
small software development teams to large development organizations.
• The Rational Unified Process encourages ongoing quality control and risk
management. Quality assessment is built into the process, in all activities and
involving all participants, using objective measurements and criteria. Risk
management is also built into the process, so that risks to the success of the project
are identified and attacked early in the process, when there is time to react.
1. Testing the individual operations associated with objects – These are functions or
procedures and the black-box and white-box approaches may be used.
2. Testing individual object classes – The principle of black-box testing is unchanged but the
notion of an equivalence class must be extended to cover related operation sequences.
4. Testing the object oriented system - V & V against the systems requirements specification
is carried out in exactly the same way as for any other type of system.
1. Use-case or scenario- based testing – Testing can be based on the scenario descriptions
and object clusters created to support the use-cases that relate to that mode of use.
2. Thread testing – Thread testing is based on testing the system’s response to a particular
input or set of input events.
8. Design Patterns
In software engineering a design pattern is defined as a “description of a solution to a
recurring problem within a context, proven by experience to lead to a superior result
when properly applied”. A design pattern isn't a finished design that can be transformed
directly into code; it is a description or template for how to solve a problem that can be used
in many different situations. Object-oriented design patterns typically show relationships and
interactions between classes or objects, without specifying the final application classes or
objects that are involved. Algorithms are not thought of as design patterns, since they solve
computational problems rather than design problems.
Patterns are a way to document good, proven, general solutions to common recurring
problems. These solutions may be applied within a specified context and serve to resolve
various forces, potential hazards that may cause problems later. Application of a pattern may
have consequences good or bad as described by the pattern.
8.1. Uses
Design patterns can speed up the development process by providing tested, proven
development paradigms. Effective software design requires considering issues that may not
become visible until later in the implementation. Reusing design patterns helps to prevent
subtle issues that can cause major problems and improves code readability for coders and
architects familiar with the patterns.
Often, people only understand how to apply certain software design techniques to certain
problems. These techniques are difficult to apply to a broader range of problems. Design
patterns provide general solutions, documented in a format that doesn't require specifics tied
to a particular problem.
8.2. Documentation
The documentation for a design pattern should contain enough information about the
problem that the pattern addresses, the context in which it is used, and the suggested
solution. Nonetheless, authors use their own layouts to document design patterns, and these
layouts usually resemble the essential parts. The authors usually include additional sections
to provide more information, and organize the essential parts in different sections, possibly
with different names.
The following is a layout which is used to document design patterns:
1. Pattern Name and Classification: Every pattern should have a descriptive and
unique name that helps in identifying and referring to it. Additionally, the pattern
should be classified according to a classification. This classification helps in
identifying the use of the pattern.
2. Problem or Intent: This section should describe the goal behind the pattern and the
reason for using it. It resembles the problem part of the pattern.
3. Motivation: This section provides a scenario consisting of a problem and a context in
which this pattern can be used. By relating the problem and the context, this section
shows when this pattern is used.
4. Applicability: This section includes situations in which this pattern is usable. It
represents the context part of the pattern.
5. Structure: A graphical representation of the pattern. Class diagrams and Interaction
diagrams can be used for this purpose.
6. Forces or Consequences: Explains the issues surrounding the problem, how the
solution resolves those issues and the potential benefits and trade-offs of applying
the solution.
7. Known Uses: Provides some descriptions of a few known situations that have
successfully applied this solution
8. Also Known As: A pattern could have more than one name. These names are
documented in this section
9. Related Patterns: This section includes other patterns that have some relation with
this pattern, so that they can be used along with this pattern, or instead of this
pattern. It also includes the differences this pattern has with similar patterns
Note: Not all published patterns will contain all of these sections and some may have
additional sections. However, all well-written software design patterns will have at least the
first six sections and, preferably, all nine.
8.3. Classification
Design patterns can be classified in terms of the underlying problem they solve. The
researchers collected 23 of the most commonly used general purpose design patterns that
are application domain independent and classified them in three categories.
Examples of problem-based pattern classifications are as follows:
1.Singleton
Pattern name & Classification – Singleton creational pattern
Problem or Intent - This is a creational design pattern which ensures that a class has only a
single occurrence (instance) and there is global point of access to it
Motivation
There are some situations where a class should have exactly one instance:
• There can be only one president for a country
• There can be only one printer spooler for a system though it can have many
printers
• There can be only one window manager for a system
Applicability
The singleton pattern is used when:
• There must be exactly one instance of a class
• It must be accessible to clients from a well known access point
• Sole instance should be extendable by sub classing, but clients should be able to use
extended class without modifying their code
Structure
Singleton
static uniqueInstance
singletonData
static Instance()
SingletonOperation()
GetsingletonData()
Consequences
Benefits
• Controlled access to single instance
• Reduced name space by avoiding global variables
2.Abstract Factory
Problem or Intent - This is a creational design pattern which provides an interface for
creating families of related objects without specifying their concrete classes.
Motivation
Consider a composite class which must contain the same members but be created differently
depending on the application. For example, you could have a document which would be
printed differently depending on the printer being used, but would still have to contain the
same information. The idea behind abstract factory is that you can pass a class (the factory)
to the constructor which has a standard interface. This interface is then used by the
constructor, but the methods it uses are implemented differently for each kind of factory
Applicability
The Abstract factory is used when:
• A system should be independent of how its products are created, composed and
represented.
• 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 to
enforce this constraint.
• You want to provide a class library of products and you want to reveal just their
interfaces not their implementations
Structure
Consequences
Benefits
• It isolates concrete classes
• It makes exchanging product families easy
• It promotes consistency among products
Drawback
• Supporting new kinds of product is difficult
3.Decorator
Pattern name & Classification – Decorator structural pattern
Problem or Intent – This is a structural pattern which attaches additional responsibilities to
an object dynamically. Decorators provide a flexible alternative to sub classing for extending
functionality.
Motivation
Sometimes it is necessary to add responsibilities to individual objects not to an entire class.
A graphical user interface toolkit, for example should let you add properties like borders or
behaviors like scrolling to any user interface component.
One way to add responsibilities is with inheritance. Inheriting a border from another class
puts a border around every sub class 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 the border.
The enclosing object is called a decorator. The decorator conforms to the interface of the
component it decorates so that its presence is transparent to the component’s clients. The
decorator forwards requests to the component and may perform additional actions (such as
drawing a border) before or after forwarding. Transparency lets you nest decorators
recursively, thereby allowing an unlimited number of added responsibilities.
For example suppose we have a TextView object that displays text in a window. TextView
has no scroll bars by default, because we might not always need them. When we do we can
use a ScrollDecorator to add them. Suppose we want to add a thick black border around the
TextView we can use a BorderDecorator to add this as well. We simply compose the
decorators with the TextView to produce the desired result.
The ScrollDecorator and BorderDecorator classes are subclasses of Decorator which is an
abstract class for visual components that decorate other visual components.
Applicability
Decorator Pattern can be applied:
• To add responsibilities to individual objects dynamically and transparently, that is
without affecting other objects.
• For responsibilities that can be withdrawn.
• When an extension by subclassing is impractical.
Structure
Consequences
Benefits
• More flexibility than static inheritance
• Avoids feature laden classes high up in the hierarchy
Drawback
• Lots of Little objects
4.Composite
Pattern name & Classification – Composite structural pattern
Problem or Intent – Compose objects into tree structures in order to represent part-whole
hierarchies. Composite lets clients treat individual objects and compositions of objects
uniformly.
Motivation – Used in situations where users need to build complex diagrams out of simple
components. For example- Building hierarchical file structures or Building graphical objects.
Applicability
Structure
Consequences
Benefits
Drawback
• Cannot restrict the components of composite by applying constraints
5.Observer
Pattern name & Classification – Observer behavioural pattern
Problem or Intent – Defines a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated automatically.
Motivation
Applicability
The Observer pattern can be used in any of the following situations:
• When an abstraction has two aspects, one dependent on the other. Encapsulating
these aspects in separate objects lets you vary and reuse them independently.
• When a change to one object requires changing others, and you don’t know how
many objects need to be changed.
• When an object should be able to notify other objects without making assumptions
about who these objects are. In other words, you don’t want these objects tightly
couples.
Structure
Consequences
Benefits
• Abstract coupling between subject and observer
• Support for broadcast communication
Drawback
• Unexpected Updates
6. Iterator
Pattern name & Classification – Iterator behavioural pattern
Problem or Intent – The intent of this design pattern is to provide a way to access the
elements of an aggregate object sequentially without exposing its underlying representation.
In other words, an Iterator allows a client to access a content of a certain data structure
without knowing about the internal representation of the contents.
Motivation - A data structure such as list should give the user a way to access its elements
in such a way that it does not expose its internal structure. Also, you should be able to
manipulate that list in different ways, depending on what you want to accomplish, but at the
same time you do not want to all your manipulation procedures into the list interface even if
you can predict which ones you might need. The Iterator Pattern allows you to do those
things. The idea of this pattern is to take the responsibility for access and manipulation of the
data structure out of the list object and put it into the Iterator object. The Iterator class will
define the interface for accessing the data structure's elements. This way we can define
different Iterators for different ways of manipulating a data structure.
Applicability
The Iterator pattern can be used in any of the following situations:
• To access an aggregate object’s contents without exposing its internal
representation.
• To support multiple traversals of aggregate objects.
• To provide a uniform interface for traversing different aggregate structures (that is to
support polymorphic iteration).
Structure
Consequences
Benefits
• Iterator Pattern supports variations in the traversal of an aggregate - Every time you
want to change the traversal algorithm, you just replace the Iterator instance with a
different one.