Professional Documents
Culture Documents
1
Title of Assignment: Write Problem Statement for System / Project
Objective:
o Identify project of enough complexity, which has at least 4-5 major functionalities
o Identify stakeholders and actors
o Prepare SRS using IEEE template
o Write detailed problem statement for your system
Relevant Theory
Conclusion:
____________________________________________________________________
____________________________________________________________________
Objective:
Identify major use cases
Identify actors
Draw use case diagram using UML 2.0 notations
Describe uses cases in a formal way
Overview:
To model a system the most important aspect is to capture the dynamic behavior. To clarify a
bit in details, dynamic behavior means the behavior of the system when it is running
/operating.
So only static behavior is not sufficient to model a system rather dynamic behavior is more
important than static behavior. In UML there are five diagrams available to model dynamic
nature and use case diagram is one of them. Now as we have to discuss that the use case
diagram is dynamic in nature there should be some internal or external factors for making the
interaction.
These internal and external agents are known as actors. So use case diagrams are consists of
actors, use cases and their relationships. The diagram is used to model the system/subsystem
of an application. A single use case diagram captures a particular functionality of a system.
So to model the entire system numbers of use case diagrams are used.
Purpose:
The purpose of use case diagram is to capture the dynamic aspect of a system. But this
definition is too generic to describe the purpose.
Because other four diagrams (activity, sequence, collaboration and Statechart) are also having
the same purpose. So we will look into some specific purpose which will distinguish it from
other four diagrams.
Now when the initial task is complete use case diagrams are modelled to present the outside
view.
Use case diagrams are considered for high level requirement analysis of a system. So when the
requirements of a system are analyzed the functionalities are captured in use cases.
So we can say that uses cases are nothing but the system functionalities written in an organized
manner. Now the second things which are relevant to the use cases are the actors. Actors can
be defined as something that interacts with the system.
The actors can be human user, some internal applications or may be some external
applications. So in a brief when we are planning to draw an use case diagram we should have
the following items identified.
Use case diagrams are drawn to capture the functional requirements of a system. So after
identifying the above items we have to follow the following guidelines to draw an efficient use
case diagram.
The name of a use case is very important. So the name should be chosen in such a way
so that it can identify the functionalities performed.
Give a suitable name for actors.
Show relationships and dependencies clearly in the diagram.
The following is a sample use case diagram representing the order management system. So if
we look into the diagram then we will find three use cases (Order, SpecialOrder and
NormalOrder) and one actor which is customer.
The SpecialOrder and NormalOrder use cases are extended from Order use case. So they have
extends relationship. Another important point is to identify the system boundary which is
shown in the picture. The actor Customer lies outside the system as it is an external user of the
system.
As we have already discussed there are five diagrams in UML to model dynamic view of a
system. Now each and every model has some specific purpose to use. Actually these specific
purposes are different angles of a running system.
So to understand the dynamics of a system we need to use different types of diagrams. Use
case diagram is one of them and its specific purpose is to gather system requirements and
actors.
These diagrams are used at a very high level of design. Then this high level design is refined
again and again to get a complete and practical picture of the system. A well structured use
case also describes the pre condition, post condition, exceptions. And these extra elements are
used to make test cases when performing the testing.
Although the use cases are not a good candidate for forward and reverse engineering but still
they are used in a slight different way to make forward and reverse engineering. And the same
is true for reverse engineering. Still use case diagram is used differently to make it a candidate
for reverse engineering.
In forward engineering use case diagrams are used to make test cases and in reverse
engineering use cases are used to prepare the requirement details from the existing
application.
So the following are the places where use case diagrams are used:
Conclusion
o _____________________________________________________________
o _____________________________________________________________
Objective:
Identify activity states and action states
Draw activity diagram with swim lanes using UML 2.0 notations for major use cases
Activity Diagram:
Overview:
Activity diagram is another important diagram in UML to describe dynamic aspects of the
system.Activity diagram is basically a flow chart to represent the flow form one activity to
another activity. The activity can be described as an operation of the system.So the control flow
is drawn from one operation to another. This flow can be sequential, branched or concurrent.
Activity diagrams deals with all type of flow control by using different elements like fork, join
etc.
Purpose:
The basic purposes of activity diagrams are similar to other four diagrams. It captures the
dynamic behavior of the system. Other four diagrams are used to show the message flow from
one object to another but activity diagram is used to show message flow from one activity to
another. Activity is a particular operation of the system. Activity diagrams are not only used for
visualizing dynamic nature of a system but they are also used to construct the executable
system by using forward and reverse engineering techniques. The only missing thing in activity
diagram is the message part.It does not show any message flow from one activity to another.
Activity diagram is some time considered as the flow chart. Although the diagrams looks like a
flow chart but it is not. It shows different flow like parallel, branched, concurrent and single.
Activity diagrams are mainly used as a flow chart consists of activities performed by the system.
But activity diagram are not exactly a flow chart as they have some additional capabilities.
These additional capabilities include branching, parallel flow, swimlane etc.
Activities
Association
Conditions
Constraints
Once the above mentioned parameters are identified we need to make a mental layout of the
entire flow. This mental layout is then transformed into an activity diagram.The following is an
example of an activity diagram for order management system. In the diagram four activities are
identified which are associated with conditions. One important point should be clearly
understood that an activity diagram cannot be exactly matched with the code. The activity
diagram is made to understand the flow of activities and mainly used by the business users.
After receiving the order request condition checks are performed to check if it is normal or
special order. After the type of order is identified dispatch activity is performed and that is
marked as the termination of the process.
The basic usage of activity diagram is similar to other four UML diagrams. The specific usage is
to model the control flow from one activity to another. This control flow does not include
messages.
The activity diagram is suitable for modeling the activity flow of the system. An application can
have multiple systems. Activity diagram also captures these systems and describes flow from
one system to another. This specific usage is not available in other diagrams. These systems can
be database, external queues or any other system.
Now we will look into the practical applications of the activity diagram. From the above
discussion it is clear that an activity diagram is drawn from a very high level. So it gives high
level view of a system. This high level view is mainly for business users or any other person who
is not a technical person.
This diagram is used to model the activities which are nothing but business requirements. So
the diagram has more impact on business understanding rather implementation details.
Conclusion :
o ________________________________________________________________
o ________________________________________________________________
Objective:
Identify analysis classes and assign responsibilities
Prepare data dictionary
Relevant Theory
Class Diagram
The Class diagram shows the building blocks of any object-orientated system. Class diagrams
depict the static view of the model or part of the model, describing what attributes and
behaviors it has rather that detailing the methods for achieving operations.
Class diagrams are most useful to illustrate relationships between classes and interfaces.
Generalizations, aggregations, and associations are all valuable in reflecting inheritance,
composition or usage, and connections, respectively.
Classes
A class is an element that defines the attributes and behaviors that an object is able to
generate. The behavior is the described by the possible messages the class is able to
understand along with operations that are appropriate for each message. Classes may also
contain definitions of constraints tagged values and stereotypes.
Class Notation
Classes are represented by rectangles which show the name of the class and optionally the
name of the operations and attributes. Compartments are used to divide the class name,
attributes and operations. Additionally constraints, initial values and parameters may be
assigned to classes.
Classes are composed of three things: a name, attributes, and operations. Below is an example
of a class.
In the diagram the class contains the class name in the topmost compartment, the next
compartment details the attributes, with the "center" attribute showing initial values.
The final compartment shows the operations, the setWidth, setLength and setPosition
operations showing their parameters.
The notation that precedes the attribute or operation name indicates the visibility of the
element,
Interfaces
An interface is a specification of behavior that implementers agree to meet. It is a contract. By
realizing an interface, classes are guaranteed to support a required behavior, which allows the
system to treat non-related elements in the same way – i.e. through the common interface.
Interfaces may be drawn in a similar style to a class, with operations specified, as shown below.
They may also be drawn as a circle with no explicit operations detailed. When drawn as a circle,
realization links to the circle form of notation are drawn without target arrows.
Generalizations
A generalization is used to indicate inheritance. Drawn from the specific classifier to a general
classifier, the generalize implication is that the source inherits the target's characteristics.
The following diagram shows a parent class generalizing a child class. Implicitly, an instantiated
object of the Circle class will have attributes x_position, y_position and radius and a method
display().
Association Classes
An association class is a construct that allows an association connection to have operations and
attributes. The following example shows that there is more to allocating an employee to a
project than making a simple association link between the two classes: the role that the
employee takes up on the project is a complex entity in its own right and contains detail that
does not belong in the employee or project class.
For example, an employee may be working on several projects at the same time and have
different job titles and security levels on each.
13 | P a g e SDM Lab Manual NBNSSOE- IT Dept
Dependencies
A dependency is used to model a wide range of dependent relationships between model
elements. It would normally be used early in the design process where it is known that there is
some kind of link between two elements but it is too early to know exactly what the
relationship is.
Later in the design process, dependencies will be stereotyped (stereotypes available include
«instantiate», «trace», «import» and others) or replaced with a more specific type of
connector.
Traces
The trace relationship is a specialization of a dependency, linking model elements or sets of
elements that represent the same idea across models. Traces are often used to track
requirements and model changes. As changes can occur in both directions, the order of this
dependency is usually ignored. The relationship's properties can specify the trace mapping, but
the trace is usually bi-directional, informal and rarely computable.
Realizations
The source objects implements or realizes the destination. Realize is used to express
traceability and completeness in the model - a business process or requirement is realized by
one or more use cases which are in turn realized by some classes, which in turn are realized by
a component, etc. Mapping requirements, classes, etc. across the design of your system, up
through the levels of modeling abstraction, ensures the big picture of your system remembers
and reflects all the little pictures and details that constrain and define it. A realization is shown
as a dashed line with a solid arrowhead and the «realize» stereotype.
Conclusion:
Hence the analysis class diagram concepts such as
Finding classes from given requirements
Finding the association among them
Finding simple attributes
Data dictionary is prepared
have been successfully understood and also implemented using java.
Objective:
Relevant Theory
A UML diagram, such as a class diagram, is typically not refined enough to provide all
the relevant aspects of a specification. There is, among other things, a need to describe
additional constraints about the objects in the model. Such constraints are often
described in natural language. Practice has shown that this will always result in
ambiguities. In order to write unambiguous constraints, so-called formal languages have
been developed. The disadvantage of traditional formal languages is that they are
usable to persons with a strong mathematical background, but difficult for the average
business or system modeler to use.
OCL has been developed to fill this gap. It is a formal language that remains easy to read
and write. It has been developed as a business modeling language within the IBM
Insurance division, and has its roots in the Syntropy method. OCL is a pure specification
language; therefore, an OCL expression is guaranteed to be without side effects. When
an OCL expression is evaluated, it simply returns a value. It cannot change anything in
the model. This means that the state of the system will never change because of the
evaluation of an OCL expression, even though an OCL expression can be used to specify
a state change (e.g., in a post-condition).
OCL is the expression language for the Unified Modeling Language (UML). To
understand OCL, the component parts of this statement should be examined. Thus, OCL
has the characteristics of an expression language, a modeling language and a formal
language.
Expression language
Modeling language
As a modeling language, all implementation issues are out of scope and cannot be
expressed in OCL. Each OCL expression is conceptually atomic. The state of the objects
in the system cannot change during evaluation.
Formal language
OCL is a formal language where all constructs have a formally defined meaning. The
specification of OCL is part of the UML specification.OCL is not intended to replace
existing formal languages, like VDM, Z etc
1. A customer can have only one account or no account with the bank.
2. A company must have one manager.
3. A marriage happened between one husband and one wife.
4. One person can work in many companies.
OCL is used to specify invariants of objects and pre- and post conditions of operations. It
makes UML (class) diagrams more precise. OCL expressions use vocabulary of UML class
diagram.
Figure shows various constraints. The OCL expression for these constraints are as
follows:
context Person
context Person
19 | P a g e SDM Lab Manual NBNSSOE- IT Dept
inv: self.fleet–>select(v | v.colour = #black)–>size <= 3
context Person
context Person
context Person
“If setAge(. . . ) is called with a non-negative argument then the argument becomes the
new value of the attribute age.”
context Person::setAge(newAge:int)
Applications of OCL
Conclusion:
____________________________________________________________________
____________________________________________________________________
Objective:
Relevant Theory
The sequence diagram is having four objects (Customer, Order, SpecialOrder and NormalOrder )
The following diagram has shown the message sequence for SpecialOrder object and the same
can be used in case of NormalOrder object. Now it is important to understand the time
sequence of message flows. The message flow is nothing but a method call of an object.
The first call is sendOrder () which is a method of Order object. The next call is confirm () which
is a method of SpecialOrder object and the last call is Dispatch () which is a method of
SpecialOrder object. So here the diagram is mainly describing the method calls from one object
to another and this is also the actual scenario when the system is running.
We have already discussed that interaction diagrams are used to describe dynamic nature of a
system. Now we will look into the practical scenarios where these diagrams are used. To
understand the practical application we need to understand the basic nature of sequence and
collaboration diagram.
The main purposes of both the diagrams are similar as they are used to capture the dynamic
behavior of a system. But the specific purposes are more important to clarify and understood.
The interaction diagrams are used when we want to understand the message flow and the
structural organization. Now message flow means the sequence of control flow from one object
to another and structural organization means the visual organization of the elements in a
system.
An example of high level sequence diagram for online bookshop. Online customer can search
book catalog, view description of a selected book, add book to shopping cart, do checkout.
Conclusion:
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Objective:
Purpose:
State chart diagram is one of the five UML diagrams used to model dynamic nature of a
system. They define different states of an object during its lifetime. And these states are
changed by events.
So State chart diagrams are useful to model reactive systems. Reactive systems can be defined
as a system that responds to external or internal events.
State chart diagram describes the flow of control from one state to another state. States are
defined as a condition in which an object exists and it changes when some event is triggered.
So the most important purpose of State chart diagram is to model life time of an object from
creation to termination.
State chart diagrams are also used for forward and reverse engineering of a system.
But the main purpose is to model reactive system.
Following are the main purposes of using State chart diagrams:
To model dynamic aspect of a system.
To model life time of a reactive system.
To describe different states of an object during its life time.
Define a state machine to model states of an object.
The door can be in one of three states: "Opened", "Closed" or "Locked". It can respond to the
events Open, Close, Lock and Unlock. Notice that not all events are valid in all states;
For example, if a door is opened, you cannot lock it until you close it. Also notice that a state
transition can have a guard condition attached: if the door is Opened, it can only respond to the
Close event if the condition doorWay->isEmpty is fulfilled.
The syntax and conventions used in state machine diagrams will be discussed in full in the
following sections.
States
A state is denoted by a round-cornered rectangle with the name of the state written inside it.
"Trigger" is the cause of the transition, which could be a signal, an event, a change in some
condition, or the passage of time.
"Guard" is a condition which must be true in order for the trigger to cause the transition.
"Effect" is an action which will be invoked directly on the object that owns the state machine as
a result of the transition.
State Actions
In the transition example above, an effect was associated with the transition. If the target state
had many transitions arriving at it, and each transition had the same effect associated with it, it
would be better to associate the effect with the target state rather than the transitions.
This can be done by defining an entry action for the state. The diagram below shows a state
with an entry action and an exit action.
It is also possible to define actions that occur on events, or actions that always occur. It is
possible to define any number of actions of each type.
Self-Transitions
A state can have a transition that returns to itself, as in the following diagram. This is most
useful when an effect is associated with the transition.
The notation in the above version indicates that the details of the Check PIN sub-machine are
shown in a separate diagram.
The following diagram shows the state machine one level up.
Exit Point
In a similar manner to entry points, it is possible to have named alternative exit points. The
following diagram gives an example where the state executed after the main processing state
depends on which route is used to transition out of the state.
Junction Pseudo-State
Junction pseudo-states are used to chain together multiple transitions. A single junction can
have one or more incoming, and one or more outgoing, transitions; a guard can be applied to
each transition. Junctions are semantic-free.
A junction which splits an incoming transition into multiple outgoing transitions realizes a static
conditional branch, as opposed to a choice pseudo-state which realizes a dynamic conditional
branch.
History States
A history state is used to remember the previous state of a state machine when it was
interrupted. The following diagram illustrates the use of history states. The example is a state
machine belonging to a washing machine.
In this state machine, when a washing machine is running, it will progress from "Washing"
through "Rinsing" to "Spinning".
If there is a power cut, the washing machine will stop running and will go to the "Power Off"
state. Then when the power is restored, the Running state is entered at the "History State"
symbol meaning that it should resume where it last left-off.
Concurrent Regions
A state may be divided into regions containing sub-states that exist and execute concurrently.
The example below shows that within the state "Applying Brakes", the front and rear brakes
31 | P a g e SDM Lab Manual NBNSSOE- IT Dept
will be operating simultaneously and independently. Notice the use of fork and join pseudo-
states, rather than choice and merge pseudo-states. These symbols are used to synchronize the
concurrent threads.
The following is an example of a State chart diagram where the state of Order object is
analyzed.
The first state is an idle state from where the process starts. The next states are arrived for
events like send request, confirm request, and dispatch order. These events are responsible
for state changes of order object.
During the life cycle of an object (here order object) it goes through the following states and
there may be some abnormal exists also. This abnormal exit may occur due to some problem
in the system. When the entire life cycle is complete it is considered as the complete
transaction as mentioned below.
The initial and final state of an object is also shown below.
State chart diagram defines the states of a component and these state changes are dynamic in
nature.
So its specific purpose is to define state changes triggered by events. Events are internal or
external factors influencing the system.
State chart diagrams are used to model states and also events operating on the system.
When implementing a system it is very important to clarify different states of an object during
its life time and state chart diagrams are used for this purpose. When these states and events
are identified they are used to model it and these models are used during implementation of
the system.
If we look into the practical implementation of State chart diagram then it is mainly used to
analyze the object states influenced by events.
Conclusion:
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
o With context of state diagram define state, do activity, entry and exit?
o What are different types of events used in state diagram?
o Explain concept of event in state model? What are different types of events?
o Explain the concept of nested state with example?
o Explain concept of concurrent sub-states?
o What is relation between class model and state model?
o What is the difference between activity diagram and sequence diagram?
Objective:
o Apply any two grasp patterns to refine the design model for your system
o Use effective UML diagrams
o Implement the system with a suitable object oriented language
Relevant Theory
GRASP Patterns
They describe fundamental principles of object design and responsibility assignment, expressed
as patterns.
After identifying your requirements and creating a domain model, then add methods to the
software classes, and define the messaging between the objects to fulfill the requirements.
The GRASP patterns are a learning aid to help one understand essential object design, and
apply design reasoning in a methodical, rational, explainable way. This approach to
understanding and using design principles are based on patterns of assigning responsibilities.
The UML defines a responsibility as "a contract or obligation of a classifier". Responsibilities are
related to the obligations of an object in terms of its behavior. Basically, these responsibilities
are of the following two types:
knowing
doing
Responsibilities are assigned to classes of objects during object design. For example, I may
declare that "a Sale is responsible for creating SalesLineltems" (a doing), or "a Sale is
responsible for knowing its total" (a knowing). Relevant responsibilities related to "knowing"
are often inferable from the domain model because of the attributes and associations it
illustrates.
POS (Point Of Sale) application is used to explain all the GRASP Patterns.
Let's understand the POS(Point Of Sale) application briefly and then apply GRASP Patterns to
POS Application.
Let's consider Point of Sale (POS) application: a Brief overview of POS application.
Problem
What is a general principle of assigning responsibilities to objects?
A Design Model may define hundreds or thousands of software classes, and an application may require
hundreds or thousands of responsibilities to be fulfilled. During object design, when the interactions
between objects are defined, we make choices about the assignment of responsibilities to software
classes. Done well, systems tend to be easier to understand, maintain, and extend, and there is more
opportunity to reuse components in future applications.
Solution
Assign a responsibility to the information expert - the class that has the information necessary to fulfill
the responsibility.
Example
Let's consider Point of Sale (POS) application: a Brief overview of POS application.
By Information Expert, we should look for that class of objects that has the information needed to
determine the total.
It is necessary to know about all the SalesLineltem instances of a sale and the sum of their subtotals.
A Sale instance contains these; therefore, by the guideline of Information Expert, Sale is a suitable class
of object for this responsibility; it is an information expert for the work.
We are not done yet. What information is needed to determine the line item
subtotal? SalesLineltem.quantity and ProductSpecification.price are needed. The SalesLineltem knows
its quantity and its associated ProductSpecification; therefore, by Expert, SalesLineltem should
determine the subtotal; it is the information expert.
In terms of an interaction diagram, this means that the Sale needs to send get-Subtotal messages to
each of the SalesLineltems and sum the results; this design is shown in Figure :
To fulfill the responsibility of knowing and answering its subtotal, a Sales- Lineltem needs to know the
product price. The ProductSpecification is an information expert on answering its price; therefore, a
message must be sent to it asking for its price.
38 | P a g e SDM Lab Manual NBNSSOE- IT Dept
Complete Class Diagram
In conclusion, to fulfill the responsibility of knowing and answering the sale’s total, three responsibilities
were assigned to three design classes of objects as follows
//...
double total = 0;
ProductSpecification prodspec
= s.getProductSpecification();
total += s.getQuantity()*prodspec.getPrice();
return total;
//...
return this.getQuantity()
productSpecification.getPrice();
Fulfillment of a responsibility may require information spread across different classes, each expert on its
own data.
Information encapsulation is maintained since objects use their own information to fulfill tasks.
This usually supports low coupling, which leads to more robust and maintainable systems. (Low
Coupling is also a GRASP pattern that is discussed in the following section).
Behavior is distributed across the classes that have the required information, thus encouraging
more cohesive "lightweight" class definitions that are easier to understand and maintain. High
cohesion is usually supported (another pattern discussed later).
Problem
How to support low dependency, low change impact, and increase reuse?
Solution
Assign responsibilities so that coupling remains low. Try to avoid one class to have to know about many
others.
There shouldn’t be too much of dependency between the modules, even if there is a
dependency it should be via the interfaces and should be minimal.
Avoid tight-coupling for collaboration between two classes (if one class wants to call the logic of
a second class, then first class needs an object of second class it means the first class creates an
object of the second class).
Inversion Of Control (IoC) / Dependency Injection (DI) - With DI objects are given their
dependencies at creation time by some third party (i.e. Java EE CDI, Spring DI…) that coordinates
each object in the system. Objects aren’t expected to create or obtain their dependencies—
dependencies are injected into the objects that need them. The key benefit of DI—loose
coupling.
This is an example of loose coupling. In this class, Traveler class is not tightly coupled
with Car or Bike implementation. Instead by applying dependency injection mechanism, the loose
coupling implementation is achieved to allow start journey with any class which has
implemented Vehicle interface.
Step 1: Vehicle interface to allow loose coupling implementation.
interface Vehicle {
@Override
System.out.println("Car is moving");
System.out.println("Bike is moving");
Step 4: Now create Traveller class which holds the reference to Vehicle interface.
class Traveler {
private Vehicle v;
return v;
this.v = v;
v.move();
Step 5: Test class for loose coupling example - Traveler is an example of loose coupling.
Problem
How to keep classes focused, understandable and manageable?
Solution
Assign responsibilities so that cohesion remains high. Try to avoid classes to do too much or too
different things.
The term cohesion is used to indicate the degree to which a class has a single, well-focused
responsibility. Cohesion is a measure of how the methods of a class or a module are meaningfully and
strongly related and how focused they are in providing a well-defined purpose to the system.
A class is identified as a low cohesive class when it contains many unrelated functions within it. And that
what we need to avoid because big classes with unrelated functions hamper their maintaining. Always
make your class small and with precise purpose and highly related functions.
The term cohesion is used to indicate the degree to which a class has a single, well-focused
responsibility. Cohesion is a measure of how the methods of a class or a module are
meaningfully and strongly related and how focused they are in providing a well-defined purpose
to the system. The more focused a class is the higher its cohesiveness - a good thing.
A class is identified as a low cohesive class when it contains many unrelated functions within it.
And that what we need to avoid because big classes with unrelated functions hamper their
maintaining. Always make your class small and with precise purpose and highly related
functions.
Example
In this example, the purpose of MyReader class is to read the resource and it does that only. It does not
implement other unrelated things. Hence it is highly cohesive.
Problem
A Controller is a non-user interface object responsible for receiving or handling a system event.
A Controller defines the method for the system operation.
Who should be responsible for handling an input event, which object/s beyond the UI layer
receives interaction?
Solution
Assign the responsibility for receiving or handling a system event message to a class
representing one of the following choices:
Represents a use case scenario within which the system event occurs, often named
<UseCaseName>Handler, <UseCaseName>Coordinator, or <Use-CaseName>Session
(use-case or session controller).
Use the same controller class for all system events in the same use case scenario.
Corollary: Note that "window," "applet," "widget," "view," and "document" classes are not on
this list. Such classes should not fulfill the tasks associated with system events, they typically
receive these events and delegate them to a controller.
Benefits
Either the UI classes or the problem/software domain classes can change without
affecting the other side.
The controller is a simple class that mediates between the UI and problem domain
classes, just forwards
output requests
Problem
Who should be responsible for creating a new instance of some class?
The creation of objects is one of the most common activities in an object-oriented system.
Consequently, it is useful to have a general principle for the assignment of creation responsibilities.
Assigned well, the design can support low coupling, increased clarity, encapsulation, and reusability.
Solution
Assign class B the responsibility to create an instance of class A if one or more of the following is true:
• B aggregates A objects.
• B contains A objects.
• B has the initializing data that will be passed to A when it is created (thus B is
B is a creator of A objects.
If more than one option applies, prefer a class B which aggregates or contains class A.
Example
Let's consider Point of Sale (POS) application: a Brief overview of POS application.
Each sale is of one or more items of one or more product types and happens at a certain date.
A product has a speci cation including a description, unitary price, and identifier.
The application also registers payments (say, in cash) associated with sales.
A payment is for a certain amount, equal or greater than the total of the sale.
Sample Code
class Sale {
List<SalesLineItem> salesLineItem
= new ArrayList<SalesLineItem>();
//...
return salesLineItem;
Benefits
Low coupling (described next) is supported, which implies lower maintenance dependencies and
higher opportunities for reuse. Coupling is probably not increased because the created class is
likely already visible to the creator class, due to the existing associations that motivated its
choice as creator.
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Objective:
Relevant Theory
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This
type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context
object whose behavior varies as per its strategy object. The strategy object changes the
executing algorithm of the context object.
Implementation
We are going to create a Strategy interface defining an action and concrete strategy
classes implementing the Strategy interface. Context is a class which uses a Strategy.
StrategyPatternDemo, our demo class, will use Context and strategy objects to
demonstrate change in Context behaviour based on strategy it deploys or uses.
Create an interface.
Strategy.java
Public interface Strategy{
Public int doOperation(int num1,int num2);
}
Step 2
OperationAdd.java
Public class OperationAdd implements Strategy{
@Override
Public int doOperation(int num1,int num2){
return num1 + num2;
}
}
OperationSubstract.java
Public class Operation Substract implements Strategy{
@Override
Public int doOperation(int num1,int num2){
return num1 - num2;
}
}
OperationMultiply.java
Public class Operation Multiply implements Strategy{
@Override
Public int doOperation(int num1,int num2){
return num1 * num2;
}
}
Step 3
Create Context Class.
Context.java
Public class Context{
Private Strategy strategy;
Use the Context to see change in behavior when it changes its Strategy.
StrategyPatternDemo.java
Public class Strategy Pattern Demo{
Public static void main(String[]args){
Context context=new Context(new OperationAdd());
System.out.println("10 + 5 = "+context.executeStrategy(10,5));
context=newContext(newOperationSubstract());
System.out.println("10 - 5 = "+context.executeStrategy(10,5));
context=newContext(newOperationMultiply());
System.out.println("10 * 5 = "+context.executeStrategy(10,5));
}
}
Step 5
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
Conclusion:
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________
Objective:
Test-driven development starts with developing test for each one of the features. The test
might fail as the tests are developed even before the development. Development team then
develops and refactors the code to pass the test.
Add a Test
Run all tests and see if the new one fails
Write some code
Run tests and Refactor code
Repeat
Context of Testing:
Valid inputs
Invalid inputs
Errors, exceptions, and events
Boundary conditions
Everything that might break
Conclusion:
____________________________________________________________________
____________________________________________________________________
____________________________________________________________________