Sei sulla pagina 1di 32

Abstract Data type

An abstract data type (ADT) is basically a logical description or a specification of components of


the data and the operations that are allowed, that is independent of the implementation.
ADTs are a theoretical concept in computer science, used in the design and analysis of algorithms,
data structures, and software systems, and do not correspond to specific features of computer
languages.
There may be thousands of ways in which a given ADT can be implemented, even when the coding
language remains constant. Any such implementation must comply with the content-wise and
behavioral description of the ADT.

When a software program is modularized, its tasks are divided into several modules based on some
characteristics. As we know, modules are set of instructions put together in order to achieve some
tasks. They are though, considered as single entity but may refer to each other to work together.
There are measures by which the quality of a design of modules and their interaction among them
can be measured. These measures are called coupling and cohesion.

Cohesion
Cohesion is a measure that defines the degree of intra-dependability within elements of a module.
The greater the cohesion, the better is the program design.

There are seven types of cohesion, namely

Co-incidental cohesion - It is unplanned and random cohesion, which might be the result of
breaking the program into smaller modules for the sake of modularization. Because it is
unplanned, it may serve confusion to the programmers and is generally not-accepted.
Logical cohesion - When logically categorized elements are put together into a module, it is
called logical cohesion.
Temporal Cohesion - When elements of module are organized such that they are processed
at a similar point in time, it is called temporal cohesion.
Procedural cohesion - When elements of module are grouped together, which are executed
sequentially in order to perform a task, it is called procedural cohesion.
Communicational cohesion - When elements of module are grouped together, which are
executed sequentially and work on same data (information), it is called communicational
cohesion.
Sequential cohesion - When elements of module are grouped because the output of one
element serves as input to another and so on, it is called sequential cohesion.
Functional cohesion - It is considered to be the highest degree of cohesion, and it is highly
expected. Elements of module in functional cohesion are grouped because they all contribute
to a single well-defined function. It can also be reused.

Coupling
Coupling is a measure that defines the level of inter-dependability among modules of a program. It
tells at what level the modules interfere and interact with each other. The lower the coupling, the
better the program.

There are five levels of coupling, namely -

Content coupling - When a module can directly access or modify or refer to the content of
another module, it is called content level coupling.
Common coupling- When multiple modules have read and write access to some global
data, it is called common or global coupling.
Control coupling- Two modules are called control-coupled if one of them decides the
function of the other module or changes its flow of execution.
Stamp coupling- When multiple modules share common data structure and work on
different part of it, it is called stamp coupling.
Data coupling- Data coupling is when two modules interact with each other by means of
passing data (as parameter). If a module passes data structure as parameter, then the
receiving module should use all its components.

Ideally, no coupling is considered to be the best.


Class and Objects

Class: In general Class is a group of similar objects, example Fruits, Vehicle, Employee, Student
etc.

Class is user defined datastructure which tieds data and functions together, it is a blueprint of
objects. Class definition will not reserve memory
In python a class can be defined using the syntax
class ClassName:
'Optional class documentation string'
Data members # to access in all the objects
Functions definition
class is a keyword and class name can be any user defined name, normally the class name will be
of title case.
A class creates a new local namespace where all its attributes are defined. Attributes may be data or
functions.
Document string is not mandetory, it can accessed using the magic function __doc__ using the
syntax. Class_name.__doc__ . docstring is used to brief description about the class.
Example:
class Student:
A class representing a student
Student-count=0
def __init__(self , n, a):
self.full_name = n
self.age = a
def get_age(self): #Method
return self.age
Student_count is a data member that can be accesed in all the methods.
__init__( )
Class functions that begins with double underscore (__) are called special functions as they have
special meaning.
__init__ is one such function that gets called when a new object is created. This function is
normally used to initialize all the instance variables.
get_age() is a method i,e a member function of student class.
Self: The first argument of every method is a reference to the current instance of the class.
In __init__, self refers to the object currently being created; so, in other class methods, it refers to
the instance whose method was called.
Object: Object is a thing which has data and exits Ex. Mango, Bike. Object is an instance
(Variable) of type Class, memmory will be resorved once the object is created. Object is a
combination of functions, variables and data structures.
Once a class is defined user can create any number of objects using the syntax
Object name=Class-name(values)
Ex: f = student(Python, 14)
Class attributes can be accessed using the syntax
Object-name.method()
Object-name.data-member
Class attributes can also be accessed using the python built in functions
getattr(obj, attribute): to access the attribute of object.(Retruns value of attribute for that object)
hasattr(obj,attribute): to check if an attribute exists or not.( Returns true if exists)
setattr(obj,name,value): to set new value to an attribute. If attribute does not exist, then it would
be created.
delattr(obj, name): to delete an attribute
One major difference between objects and class is in the way attributes and methods are treated in
objects and classes. A class is a definition about objects; the attributes and methods in a class are
thus declarations that do not contain values. However, objects are created instances of a class. Each
has its own attributes and methods. The values of the set of attributes describe the state of the
objects.

Class members: (Data member and Member function)


1. Data Members: Variables defined in a class are called data memebers. There are types of fields

Class Variables: The variables accessed by all the objects(instances) of a class are called
class variable. There is only copy of the class variable and when any one object makes a change to a
class variable, the change is reflected in all the other instances as well. Class variables can be
accessed using the syntax

Class_name.Class variable
Object_name. Class variable
Note: if user changes the value of class variable using class name, then it reflects to all objects
if user changes the value of class variable using object name, then it reflects only to
that objects
Object/instance Variable: Variables owned by each individual object (instance of a class)
are called object variables. Each object has its own copy of the field i.e. they are not shared and are
not related in any way to the field by the same name in a different instance of the same class.
In the above Student class example Student-count is Class variable and full_name is a
Object variable.

2. Member function(method): A method is a function that is defined inside a class. Methods are
members of classes. A method is a function that is available for a given object. There are different
types of methods like Class methods, Instance methods, Service methods, and Support methods.

Class method: A "class method" is a method where the initial parameter is not an instance
object(self), but the class object , which by convention is called cls . This is implemented with the
@classmethod decorator. The class method does not require object to invoke it.

Ex:
class Foo(object):
@classmethod
def hello(cls):
print("hello from %s" % cls.__name__)
Foo.hello()
-> "Hello from Foo"
Foo().hello()
-> "Hello from Foo"

Instance Method:An "Instance method" is a method where the initial parameter is an instance of
object(self) and requires no decorator. These are the most common methods used.
class Foo(object):
def hello(self):
print("hello)

f=Foo()

f.hello()
Built-in Class attributes:Every Python class keeps the following built-in attributes and they can be
accessed using dot operator like any other attribute.
__dict__: Dictionary containing the class's namespace.
__doc__: Class documentation string or none, if undefined.
__name__: Class name.
__module__: Module name in which the class is defined. This attribute is
"__main__" in interactive mode

Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name,", Salary: ", self.salary)
emp1 = Employee("Ranga", 2000)
emp2 = Employee("Soma", 5000)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__ )
Classes and functions: Program
Encapsulation : Encapsulation is the mechanism of embeding the data with function for restricting
the access to some of an objects's components, this means, that the internal representation of an
object can't be seen from outside of the objects definition.
Encapsulation provides the different levels of accessing to the class members this is called visibility
of class members. OOPs languages provides three access specifiers to controll the accessing of class
members.
Private: This specifies that the class members (variables and methods) can be accessed only within
that class means that only the member functions can use the class members and can not be used
outside the class. In C++ all the members are private by default. In python to make the class
member private begin the name of the member with double under_score(__)
Example:
class Visibility:
def __init__(self,a,b):
self.atta=a
self.__attb=b #private data
def __disp(self):# private method
print ("Inside private method",self.atta,self.__attb)
def display(self):
print("Inside public method",self.atta)
self.__disp()#calling private method
ob1=Visibility(2,20)
ob1.display()
ob1.__disp()# will not work as it can not access outside

Public: This specifies that all attributes and methods are visible to every one. Class members can
be accesed even outside the class using object_name.class member. In C++ to make the class
members public, have all the members in the public: section.
In pyhton by defalut all the members are public.
Example:
class Cup:
def __init__(self):
self.color = None
self.content = None

def fill(self, beverage):


self.content = beverage
def empty(self):
self.content = None
redCup = Cup()
redCup.color = "red"
redCup.content = "tea"
redCup.empty()
redCup.fill("coffee")

Shows all members are public

Protected: This specifies that class members are accessible only


within the class and its sub-class. In python to make the class
member protected begin the name of the member with single
under_score(_).

Example:
class Cup:
def __init__(self):
self.color = None
self._content = None # protected variable

def fill(self, beverage):


self._content = beverage
def empty(self):
self._content = None
redCup = Cup("red")
redCup._Cup__content = "tea"

Note :Even the variable content is protected it is accessable.


Object initialization: Assiging the values to objects when they are created is called object
intialization. Constructor is used to initialize objects. Constructor is a special method which is
called when a new instance of a class (object) is created. In python __init__( ) method is used as
initialization method called class constructor.
Example:
class Student:
... def __init__(self,na,ag,fe):
... self.name=na
... self.age=ag
... self.fee=fe
...
>>> s1=Student('Ranga',22,25000)
>>> s2=Student('Soma',25,38000)
Here the objects S1 and S2 are initialized to specified values.

Destructor: Destructor is member function, which is invoked when the instance is about to be
destroyed. This method is used to cleanup the resources used by an instance. Destructor is used for
destroying the objects which are not needed, to free the memory space. The process of periodically
reclaiming the block of memory that are no longer needed is called Garbage collection. In
python Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of

aliases that point to it changes.


In pyhton __del__(self ) method is used as destructor.
Example:
class Point:
def __init( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2)) # prints the ids of the obejcts)
del pt1
del pt2
del pt3

Method and Message:


Message: Objects communicate with one another by sending messages. A message is a method call
from a message-sending object to a message-receiving object. A message- sending object is a sender
while a message-receiving object is a receiver. The set of methods collectively defines the dynamic
behavior of an object. An object may have as many methods as required. A message contains 3
components.
an object identifier that indicates the message receiver,
a method name (corresponding to a method of the receiver), and
arguments (additional information required for the execution of the method).
Example:
Ranga as an Object
Attributes:
name = " Ranga "
address = " 1, MCA,RVCE "
budget = " 2000 "
Methods:
purchase() {
Soma.takeOrder("Ranga", "sofa", "1, mca rvce",
"12 November")
}
getBudget()
{return budget}
The message Soma.takeOrder(who , stock , address , date) is interpreted as
follows:
Soma is the receiver of the message;
takeOrder() is a method call on Soma;
"Ranga" , "stock" , "address" , "date" are arguments of the message.
Method: A method in object-oriented programming (OOP) is a procedure associated with a
message and an object. A message is valid if the receiver has a method that corresponds to the
method named in the message and the appropriate arguments, if any, are supplied with the message.
Method Signature: A method signature is part of the method declaration. It is the combination of
the method name and the parameter list.
Method Overloading: It is the capability of definig the several functions with same name that
performs similar task, but on different data types. In python Method over loading is not supported
as it conciders only the recenst(last) function definition.
Example: def add(a,b):
return a+b
def add(a,b,c):
return a*b*c
print add(2,3)# will not work as python takes only the recent definition.
Operator Overloading:The feature that allows the defination of different behaviour for a language
built-in operator, depending on the data type is called Operator overloading. For example + operator
in can be used perform arithmetic addition of numbers and can also be used concatinate two strings.
In python for overloading the existing operators user have to define the respective spe-cial function
as shown in the table 1 and table 2 respectively.
Inheritance: In object Oriented Programming inheritance is the ability to define a new class that is
a modified version of an existing class.
The primary advantage of this feature is that you can add new methods to a class without modifying
the existing class. The existing class is called as Super Class/Parent class. A Subclass, "derived
class", heir class, or child class is a derivative class which inherits the properties (methods and
attributes) from one are more super classes.
Inheritance is a powerful feature. Some programs that would be complicated without inheritance
can be written concisely and simply with it. Inheritance can facilitate code reuse, since you can
customize the behavior of parent classes without having to modify them.
Disadvantage of inheritance is that it make programs difficult to read. When a method is invoked,
it is sometimes not clear where to find its definition. The relevant code may be scattered among
several modules.
In Inheritance base class and child classes are tightly coupled. Hence If you change the code of
parent class, it will get affects to the all the child classes.
Types of Inheritance: Single:In this inheritance, a derived class is created from a single base class.
Multi level:In this inheritance, a derived class is created from another derived class.
Multiple: In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F# etc.
Hierarchical inheritance: In this inheritance, more than one derived classes are created from a
single base.
Hybrid inheritance: This is combination of more than one inheritance. Hence, it may be a
combination of Multilevel and Multiple inheritance or Hierarchical and Multilevel inheritance or
Hierarchical and Multipath inheritance or Hierarchical, Multilevel and Multiple inheritance.
Uninheritable classes:
Inheritance in python: Python supports multiple inheritance i.e a sub-class can be derived from
more than one base class. The child class inherits the attributes of its parent class, and user can use
those attributes as if they were defined in the child class. A child class can also override data
members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of base classes
to inherit from is given after the class name
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite.
Example:
class Player(object):
''' base class'''
def __init__(self,name,mobile):
self.name=name
self.mobile=mobile
def __str__(self):
return "%s mobile number is %d" % (self.name, self.mobile)
class Crick_player(Player):
def __init__(self, name,mobile,Noruns,Nowickets):
Player.__init__(self, name,mobile)
self.Noruns=Noruns
self.Nowickets=Nowickets
def __str__(self):
return "%s scored %d runs and taken %d wickets, his mobile number is %d"
class, indicates that we are creating a class, The second word, Player, indicates the name of the
class, object is a special variable in Python that you should include in the parentheses when you are
creating a new class. In the second class defination Crick_player is a sub-class and Player is a
base-class
The issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a
subclass of the superclass sup.
The isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an
instance of a subclass of Class.
Method Overriding:Method overriding, in object oriented programming, is a language feature that
allows a subclass or child class to provide a specific implementation of a method that is already
provided by one of its superclasses or parent classes. The implementation in the subclass overrides
(replaces) the implementation in the superclass by providing a method that has same name, same
parameters or signature, and same return type as the method in the parent class(wiki).
If an object of a parent class is used to invoke the method, then the version in the parent class will
be executed, but if an object of the subclass is used to invoke the method, then the version in the
child class will be executed.
Example:
class Thought(object):
def __init__(self):
pass
def message(self):
print "I feel like I am diagonally parked in a parallel universe."

class Advice(Thought):
def __init__(self):
super(Advice, self).__init__()
def message(self):
print "Warning: Dates in calendar are closer than they appear"
super(Advice, self).message()

Method Resolution Order in Python


The Python Method Resolution Order defines the class search path used by Python to search for the
right method to use in classes having multi-inheritance.

class X: pass
class Y: pass
class Z: pass
class A(X,Y): pass
class B(Y,Z): pass
class M(B,A,Z): pass
# Output:
# [<class '__main__.M'>, <class '__main__.B'>,
# <class '__main__.A'>, <class '__main__.X'>,
# <class '__main__.Y'>, <class '__main__.Z'>,
# <class 'object'>]
Exception:
An exception is an event, which occurs during the execution of a program that disrupts the normal
flow of the program's instructions. Even if a statement or expression is syntactically correct, it may
cause an error when an attempt is made to execute it. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. In Python exception is an object that
represents an error.
Exception Handling:If there is some suspicious code which may raise an exception, then place
the suspicious code in a try: block. After the try: block, include an except: statement, followed by a
block of code which handles the problem as elegantly as possible.
Standard Exceptions in Python:
Syntax:
try:
statements to be executed
-------
-------
except ExceptionI:
If there is ExceptionI, then execute this block.
-------------
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
-----------------------------

A single try statement can have multiple except statements. This is useful when the try block
contains statements that may throw different types of exceptions.
You can also provide a generic except clause, which handles any exception.
After the except clause(s), you can include an else-clause. The code in the else-block
executes if the code in the try: block does not raise an exception.
The else-block is a good place for code that does not need the try: block's protection.
Example:
sname=input("Enter Existing file name")
dname=input("Enter new file name")
try:
sh=open(sname, "r")
dh = open(dname, "w")
str=sh.read()
dh.write(str)
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("File successfully copied")
sh.close()
dh.close()
except clacuse with no exceptions.
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
If no specific exception is specified then it catches all the exceptions that occurs. But drawback of
this kind is the programmer can not identify the root cause of the problem.
Except clause with multiple exceptions:
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,then execute this block.
......................
else:
If there is no exception then execute this block.

Abstract Class: An abstract class is a class that cannot be directly instantiated. Instead, you
instantiate an instance of a subclass. Typically, an abstract class has one or more operations that are
abstract. An abstract operation has no implementation; it is pure declaration so that clients can bind
to the abstract class. The most common way to indicate an abstract class or operation in the UML is
to italicize the name.

You can also make properties abstract, indicating an abstract property or accessor methods. Italics
are tricky to do on a whiteboards, so you can use the label: {abstract}.
Dynamic Binding:Dynamic binding also called dynamic dispatch is the process of linking
procedure call to a specific sequence of code (method) at run-time. It means that the code to be
executed for a specific procedure call is not known until run-time. Dynamic binding is also known
as late binding or run-time binding.
Dynamic binding is an object oriented programming concept and it is related with polymorphism
and inheritance.
Deligation: In object-oriented programming, delegation refers to evaluating a member (property or
method) of one object (the receiver) in the context of another, original object (the sender).
Delegation can be done explicitly, by passing the sending object to the receiving object, which can
be done in any object-oriented language; or implicitly, by the member lookup rules of the language,
which requires language support for the feature. Implicit delegation is the fundamental method for
behavior reuse in prototype-based programming, corresponding to inheritance in class-based
programming.
Class Library:In object-oriented programming , a class library is a collection of prewritten classes
or coded templates, any of which can be specified and used by a programmer when developing an
application program. The programmer specifies which classes are being used and furnishes data that
instantiate s each class as an object that can be called when the program is executed. Access to and
use of a class library greatly simplifies the job of the programmer since standard, pretested code is
available that the programmer doesn't have to write. In python import stament is used include the
prewritten modules into the required script.
Model:A model is a simplification of reality. Modeling is a proven and well-accepted engineering
technique. A model provides the blueprints of a system. Models may encompass detailed plans, a
good model includes those elements that have broad effect and omits those minor elements that are
not relevant to the given level of abstraction. Every system may be described from different aspects.
We build models so that we can better understand the system we are developing.
Through modeling, we achieve four aims.
1. Models help us to visualize a system as it is or as we want it to be.
2. Models permit us to specify the structure or behavior of a system.
3. Models give us a template that guides us in constructing a system.
4. Models document the decisions we have made.
In software the two most common ways are from
1) An algorithmic perspective
2)An object-oriented perspective.
In algorithmic approach the main building block of all software is the procedure or function. This
view leads developers to focus on issues of control and the decomposition of larger algorithms into
smaller ones.
In object-oriented approach, the main building block of all software systems is the object or class.
A Modeling language is a language whose vocabulary and rules focus on the conceptual and
physical representation of a system.
UML(Unified Modeling Language):The Unified Modeling Language (UML) is a standard
language for writing software blueprints. The UML may be used to visualize, specify, construct, and
document the artifacts of a software system. The Unified Modeling Language (UML) is a family of
graphical notations,that help in describing and designing software systems, particularly software
systems built using the object-oriented (OO) style.
UML builds the model that are precise, unambiguous, and complete. It addresses the
specification of all the important analysis, design, and implementation decisions that must
be made in developing and deploying a software system.
UML is not a visual programming language, but its models can be directly connected to a
variety of programming languages i.e UML model can be directly mapped to programming
OOP languages. This mapping permits forward engineering: The generation of code from a
UML model into a programming language. The reverse is also possible: You can reconstruct
a model from an implementation back into the UML.
UML addresses the documentation of a system's architecture and all of its details. software
organization produces all sorts of artifacts in addition to raw executable code.
These artifacts include (but are not limited to) Requirements, Architecture, Design,
Source code, Project plans, Tests, Prototypes, Releases.
Building Blocks of the UML: UML encompasses three kinds of building blocks
1. Things 2. Relationships 3. Diagrams

Things
Things are the basic object-oriented building blocks of the UML. There are four kinds of things in
the UML:
a). Structural things b). Behavioral things c). Grouping things d). Annotational things
Structural things: are the nouns of UML models. These are the mostly static parts of a model,
representing elements that are either conceptual or physical. There are seven kinds of structural
things.

Class: A class is a description of a set of objects that share the same attributes, operations,

relationships, and semantics. Graphically, a class is rendered as a rectangle, usually including its
name, attributes, and operations.

Interface:An interface is a collection of operations that specify a service of a class or component.


An interface defines a set of operation specifications (that is, their signatures). Graphically, an
interface is rendered as a circle together with its name. An interface rarely stands alone. Rather, it is
typically attached to the class or component that realizes the interface.

Collabrations:a collaboration defines an interaction and is a society of roles and other elements
that work together to provide some cooperative behavior that's bigger than the sum of all the
elements, given class might participate in several collaborations. Graphically, a collaboration is
rendered as an ellipse with dashed lines, usually including only its name,

Use Case:use case is a description of set of sequence of actions that a system performs that yields
an observable result of value to a particular actor. A use case is used to structure the behavioral
things in a model. A use case is realized by a collaboration. Graphically, a use case is rendered as an
ellipse with solid lines, usually including only its name.

Active Class: An active class is a class whose objects own one or more processes or threads and
therefore can initiate control activity. An active class is just like a class except that its objects
represent elements whose behavior is concurrent with other elements. Graphically, an active class is
rendered just like a class, but with heavy lines, usually including its name, attributes and operations.

Component: a component is a physical and replaceable part of a system that conforms to and
provides the realization of a set of interfaces. components may be the artifacts of the development
process, such as source code files. A component typically represents the physical packaging of
otherwise logical elements, such as classes, interfaces, and collaborations. Graphically, a component
is rendered as a rectangle with tabs, usually including only its name.

Node: A node is a physical element that exists at run time and represents a computational resource,
generally having at least some memory and often, processing capability. Graphically, a node is
rendered as a cube, usually including only its name.

2. Behavioral Things: Behavioral things are the dynamic parts of UML models. These are the
verbs of a model, representing behavior over time and space. There are two primary kinds of
behavioral things.
Interaction : An interaction is a behavior that comprises a set of messages exchanged among a set
of objects within a particular context to accomplish a specific purpose. The behavior of a society of
objects or of an individual operation may be specified with an interaction. Graphically, a message is
rendered as a directed line, almost always including the name of its operation.
State Machine: A state machine is a behavior that specifies the sequences of states an object or an
interaction goes through during its lifetime in response to events, together with its responses to
those events. The behavior of an individual class or a collaboration of classes may be specified with
a state machine. Graphically, a state is rendered as a rounded rectangle, usually including its name
and its substates, if any

3. Grouping things: are the organizational parts of UML models. These are the boxes into which a
model can be decomposed. In all, there is one primary kind of grouping thing, namely, packages.
Package: A package is a general-purpose mechanism for organizing elements into groups.
Structural things, behavioral things, and even other grouping things may be placed in a package.
Graphically, a package is rendered as a tabbed folder, usually including only its name and,
sometimes, its contents.

Annotational things:are the explanatory parts of UML models. These are the comments you may
apply to describe, illuminate, and remark about any element in a model. There is one primary kind
of annotational thing, called a note.
Note :A note is simply a symbol for rendering constraints and comments attached to an element or a
collection of elements. Graphically, a note is rendered as a rectangle with a dog-eared corner,
together with a textual or graphical comment.

Relationships
A relationship is a connection among things, Graphically, a relationship is rendered as a path, with
different kinds of lines used to distinguish the kinds of relationships.
There are four kinds of relationships in the UML:
Dependency
Association
Generalization
Realization
1. Dependency: A dependency is a using relationship that states that a change in specification of one
thing (for example, class Channel) may affect another thing that uses it (for example, class Filim
Clip), but not necessarily the reverse. Graphically, a dependency is rendered as a dashed directed
line, directed to the thing being depended on. Use dependencies when you want to show one thing
using another.

Example:

2. Association:an association is a structural relationship that describes a set of links, a link being a
connection among objects. association is a structural relationship that specifies that objects of one
class are connected to objects of another. Given an association connecting two classes, you can
navigate from an object of one class to an object of the other class, and vice versa. Graphically, an
association is rendered as a solid line, possibly directed, occasionally including a label, and often
containing other adornments, such as multiplicity and role names.

The multiplicity of a property is an indication of how many objects may fill the property. The most
common multiplicities are,
1 exactly one object
0..1 ( may or may not have a single object)
* (0 object or there is no upper limit to the number of objects.

Example:

Aggregation: A plain association between two classes represents a structural relationship


between peers, meaning that both classes are conceptually at the same level, no one more important
than the other. This is used to model a "whole/part" relationship in which one class represents a
larger thing (the "whole"), which consists of smaller things (the "parts"). This kind of relationship is
called aggregation, which represents a "has-a" relationship, meaning that an object of the whole has
objects of the part. Graphically, a generalization relationship is rendered as a solid line with an open
diamond at the whole end.
3. Generalization: a generalization is a specialization/generalization relationship in which objects
of the specialized element (the child) are substitutable for objects of the generalized element (the
parent). In this way, the child shares the structure and the behavior of the parent. Graphically, a
generalization relationship is rendered as a solid line with a hollow arrowhead pointing to the
parent. Generalization is sometimes called an "is-a-kind-of" relationship

Example:

4. Realization: A realizationis a semantic relationship between classifiers in which one classifier


specifies a contract that another classifier guarantees to carry out. Graphically, a realization is
rendered as a dashed directed line with a large open arrowhead pointing to the classifier that
specifies the contract.

Example:
Diagrams in the UML
A diagram is the graphical presentation of a set of elements, most often rendered as a connected
graph of vertices (things) and arcs (relationships).
1. Class diagram
2. Object diagram
3. Component diagram
4. Deployment diagram. 1 to 4 conceptualize the static part of system
5. Use case diagram
6. Sequence diagram
7. Collaboration diagram
8. Statechart diagram
9. Activity diagram 5 to 9 conceptualize the dynamic(behavioral) part of system

Class Diagram: A class diagram shows a set of classes, interfaces, and collaborations and their
relationships.A class diagram describes the types of objects in the system and the various kinds of
static relationships that exist among them. Class diagrams also show the properties and operations
of a class and the constraints that apply to the way objects are connected.
Object Diagram: An object diagram is a graph of instances, including objects and data values for
things found in the class diagram. A static object diagram is an instance of a class diagram; it shows
the static snapshot of the detailed state of a system at a point in time. An object diagram shows a
set of objects and their relationships.
Object diagrams commonly contain
Objects
Links
Like all other diagrams, object diagrams may contain notes and constraints.

Object Interaction Diagram: An interaction diagram shows an interaction, consisting of a set of


objects and their relationships, including the messages that may be dispatched among them. A
sequence diagram is an interaction diagram that emphasizes the time ordering of messages.
Graphically, a sequence diagram is a table that shows objects arranged along the X axis and
messages, ordered in increasing time, along the Y axis.
A sequence diagram shows, as parallel vertical lines (lifelines), different processes or objects that
live simultaneously, and, as horizontal arrows, the messages exchanged between them, in the order
in which they occur. In Sequence diagram solid arrow heads represent synchronous calls, open
arrow heads represent asynchronous messages, and dashed lines represent reply messages.
Activation boxes, or method-call boxes, are opaque rectangles drawn on top of lifelines to
represent that processes are being performed in response to the message.
State transition Diagram: a state diagram describes the behavior of a single object in response to a
series of events in a system. Sometimes it's also known as a Harel state chart or a state machine
diagram. This UML diagram models the dynamic flow of control from state to state of a particular
object within a system. A state machine is a behavior that specifies the sequences of states an object
goes through during its lifetime in response to events, together with its responses to those events.

Transition
A solid arrow represents the path between different states of an object. Label the transition with the
event that triggered it and the action that results from it. A state can have a transition that points
back to itself.

Initial State
A filled circle followed by an arrow represents the object's initial state.
Final State
An arrow pointing to a filled circle nested inside another circle represents the object's final state.

Example:

Use case diagram:Use case diagrams are usually referred to as behavior diagrams used to describe
a set of actions (use cases) that a system can perform in collaboration with one or more external
users of the system (actors). It also specifies the relationship between use case and actor. Use cases
are a technique for capturing the functional requirements of a system.
Use case diagrams commonly contain
Use cases (Functionalities)
Actors
Dependency, generalization, and association relationships
Use case: A use case is a set of scenarios (actions) tied together by a common user goal.
Actor: An actor is a role that a user plays with respect to the system. Actors carry out use cases. A
single actor may perform many use cases; conversely, a use case may have several actors
performing it.
Shows Two or more Player actors are involved in the Play Game use case. Each Player participates
in one Play Game.

Use case diagram for Order Managment system.

Use cases can be organized showing <<Include>>, <<Extended>> and Generalization


relationship.
Includes:Use case include is a directed relationship between two use cases which is used to show
that behavior of the included use case (the addition) is inserted into the behavior of the including
(the base) use case. Included use cases can be useful for a complex step that would divide the main
scenario or for steps that are repeated in several use cases. Include use cases are required and not
optional.
Extended:Extend is a directed relationship that specifies how and when the behavior defined in
additional use case (optional) is implicitly incorporated into the base use case for extending the
behaviour. The base use case may stand alone, but under certain conditions, its behavior may be
extended by the behavior of another use case.

Generalization: Generalization among use cases is just like generalization among classes. Here it
means that the child use case inherits the behavior and meaning of the parent use case; the child
may add to or override the behavior of its parent; and the child may be substituted any place the
parent appears (both the parent and the child may have concrete instances).

Scenario: A scenario
is a sequence of steps describing an interaction between a user and a system. So if we have a Web-
based on- line store, we might have a Buy a Product scenario that would say this:
The customer browses the catalog and adds desired items to the shopping basket. When the
customer wishes to pay, the customer describes the shipping and credit card information and
confirms the sale. The system checks the authorization on the credit card and confirms the sale both
immediately and with a follow-up email.
System boundary : The rectangle around the use cases is called the system boundary box and as
the name suggests it indicates the scope of the system - the use cases inside the rectangle represent
the functionality that you intend to implement.

http://www.geeksforgeeks.org/command-pattern/(command pattren example)

Command Pattren:Definition: The command pattern encapsulates a request as an object, thereby


letting us parameterize other objects with different requests, queue or log requests, and support
undoable operations.
The definition is a bit confusing at first but lets step through it. In analogy to our problem above
remote control is the client and stereo, lights etc. are the receivers. In command pattern there is a
Command object that encapsulates a request by binding together a set of actions on a specific
receiver. It does so by exposing just one method execute() that causes some actions to be invoked
on the receiver.

Parameterizing other objects with different requests in our analogy means that the button used to
turn on the lights can later be used to turn on stereo or maybe open the garage door.

queue or log requests, and support undoable operations means that Commands Execute operation
can store state for reversing its effects in the Command itself. The Command may have an added
unExecute operation that reverses the effects of a previous call to execute.It may also support
logging changes so that they can be reapplied in case of a system crash.
Intent: Encapsulate a request in an object and allows the parameterization of clients with
different requests, saving the requests in a queue.
Participants:
Command - declares an interface for executing an operation;
ConcreteCommand - extends the Command interface, implementing the Execute method
by invoking the corresponding operations on Receiver. It defines a link between the
Receiver and the action.
Client - creates a ConcreteCommand object and sets its receiver;
Invoker - asks the command to carry out the request;
Receiver - knows how to perform the operations;

Potrebbero piacerti anche