0% found this document useful (0 votes)
30 views

Ooad Unit IV

The document discusses various object-oriented design (OOD) principles and patterns. It covers GRASP principles like creator, information expert, low coupling, high cohesion, and controller. It also discusses design patterns categories like creational (factory method), structural (bridge, adapter) and behavioral (strategy, observer). Key creational pattern discussed in more detail is factory method pattern. The document provides examples and benefits of applying these OOD techniques.

Uploaded by

S Divya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Ooad Unit IV

The document discusses various object-oriented design (OOD) principles and patterns. It covers GRASP principles like creator, information expert, low coupling, high cohesion, and controller. It also discusses design patterns categories like creational (factory method), structural (bridge, adapter) and behavioral (strategy, observer). Key creational pattern discussed in more detail is factory method pattern. The document provides examples and benefits of applying these OOD techniques.

Uploaded by

S Divya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT- IV DESIGN PATTERNS

GRASP: Designing objects with responsibilities – Creator – Information expert – Low Coupling
– High Cohesion – Controller Design Patterns – creational – factory method – structural –
Bridge – Adapter – behavioural – Strategy – observer –Applying GoF design patterns – Mapping
design to code.

DESIGN PATTERNS

GRASP: General Responsibility Assignment Software Patterns


 GRASP is a learning aid that helps to understand essential object design and apply design
reasoning in a methodical, rational and explainable way.
 GRASP is used as a tool to help master the basics of OOD and understanding
responsibility assignment in object design.
 There are nine basic OO design principles in GRASP. They are,
1. Creator
2. Information Expert
3. Low Coupling
4. High Cohesion
5. Controller
6. Polymorphism
7. Pure Fabrication
8. Indirection
9. Protected Variations

CREATOR

Creation of objects is one of the most common activities in an object oriented system. Which
class is responsible for creating objects is a fundamental property of relationship between objects
of particular classes.

Problem

Who should be responsible for creating a new instance of some class?

Solution:

Assign class B the responsibility to create an instance of a class A if one of these is true,

 B contains or compositely aggregates A


 B records A
 B closely uses A
 B has the initializing data for A that will be passed to A when it is created.

Thus B is an expert with respect to creating A


B is a creator of A objects

INFORMATION EXPERT

Problem

What is a general principle of assigning responsibilities to objects?


Solution:
Assign a responsibility to the information expert-the class that has the information
necessary to fulfill the responsibility.

LOW COUPLING
Coupling is a measure of how strongly one element is connected to, has knowledge of, or relies
on other elements. An element with low (or weak) coupling is not dependent on too many other
elements.
A class with high (or strong) coupling relies on many other classes. Such classes may be
undesirable; some suffer from the following problems,
 Forced local changes because of changes in related classes.
 Harder to understand in isolation.
 Harder to reuse because its use requires the additional presence of the classes on which it
is dependent.

Problem
How to support low dependency, low change impact, and increased reuse?

Solution:
Assign a responsibility so that coupling remains low.
Eg: Partial Class domain

Assume that a Payment instance is to be created and associated with the Sale. Since a Register
"records" a Payment in the real-world domain, the Creator pattern suggests Register as a
candidate for creating the Payment.

The Register instance could then send an addPayment message to the Sale, passing along the
new Payment as a parameter.

Fig: Register creates Payment

Assignment of responsibilities couples the Register class to knowledge of payment class.


Alternative solution to create payment and associate it with Sale.

Fig: Sales creates Payment

HIGH COHESION

Cohesion
Cohesion is a measure of how strongly related and focused the responsibilities of an element
are. An element with highly related responsibilities, and which does not do a tremendous amount
of work, has high cohesion. These elements include classes, subsystems, and so on.

Problem
How to keep objects focused, understandable, and manageable, and as a side effect,
support Low Coupling?
Solution:
Assign a responsibility so that cohesion remains high.
A class with low cohesion does many unrelated things, or does too much work. Such classes are
undesirable; they suffer from the following problems:
 Hard to comprehend
 Hard to reuse
 Hard to maintain
 Delicate; constantly affected by change.

Example
Assume that a Payment instance is to be created and associate it with the Sale. What class should
be responsible for this? Since Register records a Payment in the real-world domain, the Creator
pattern suggests Register as a candidate for creating the Payment. The Register instance could
then send an addPayrnent message to the Sale, passing along the new Payment as a parameter.

Fig: Register creates payment


This assignment of responsibilities places the responsibility for making a payment in the
Register.
Fig: Sale creates Payment

CONTROLLER

A Controller is the first object beyond the UI layer that is responsible for receiving or handling a
system operation message.

Problem

What first object beyond the UI layer receives and coordinates(controls) a system operation?

Solution:

Assign the responsibility to a class representing one of the following choices,

 Represents the overall system, “a root object”, a device that the software is running
within, or a major subsystem.
 Represents a use case scenario within which the system event occurs.

Example: NextGen POS application


Fig: Assigning responsibilities to controller class

During design, a controller class is assigned the responsibility for system operation.

The system Operations identified during system behaviour analysis are assigned to one or more
controller classes, such as Register,

Fig: Controller Class

Bloated Controller

Poorly designed, a controller class will have low cohesion. unfocused and handling
too many areas of responsibility; this is called a bloated controller.

Signs of bloating include:


 There is only a single controller class receiving all system events in the system, and there
are many of them.
 The controller itself performs many of the tasks necessary to fulfill the system event,
without delegating the work
 A controller has many attributes, and maintains significant information about the system
or domain, which should have been distributed to other objects, or duplicates information
found elsewhere.
Cures for a bloated controller

 Add more controllers-a system does not have to have only one. For example, consider an
application with many system events, such as an airline reservation system.

 Design the controller so that it primarily delegates the fulfillment of each system
operation responsibility on to other objects.

DESIGN PATTERNS

 Design patterns are termed as reusable solutions for commonly occurring problems in
software designs.
 Design Patterns are descriptions of communicating objects and classes customized to
solve a general design problem in a particular context.
 Design Patterns identifies the participating classes and instances, their roles and
collaborations, and the distribution of responsibilities.

Essential Elements of a pattern:


1. Pattern Name
2. Problem
3. Solution
4. Consequences

Design Patterns are Categorized into,

1. Creational Pattern
 Factory Method
2. Structural Patterns
 Bridge
 Adapter
3. Behavioral Patterns
 Strategy
 Observer
CREATIONAL PATTERN

Creational design patterns provide a way to create objects while hiding the creation logic, rather
than instantiating objects directly using new operator. This gives program more flexibility in
deciding which objects need to be created for a given use case.

FACTORY METHOD

Name: Factory
Problem: Who should be responsible for creating objects when there are special considerations, such
as complex creation logic, a desire to separate the creation responsibilities for better cohesion, and so
forth? Solution: Create a Pure Fabrication object called a Factory that handles the creation.

Advantages of Factory objects

 Separate the responsibility of complex creation into cohesive helper objects.


 Hide potentially complex creation logic.
 Allow introduction of performance-enhancing memory management strategies, such as object
caching or recycling.

In the below diagram, In ServicesFactory, the logic to decide which class to create is resolved by
reading in class name from an external source and then dynamically loading the class. This is termed
as Partial Data Driven Design.

Fig: Factory Pattern


Benefits of Factory Method
 Factory method introduces a separation between the application and a family of classes. It
provides a simple way of extending the family of products with minor changes in the
application code
 It provides customization hooks. When the objects are created directly inside the class, it
is hard to replace them by objects which extend their functionality. If a factory is used
instead to create a family of objects that customizes objects can easily replace the original
objects, configuring the factory to create them.

Drawbacks of Factory Method


 The Factory has to be used for a family of objects. If the classes doesn’t extend
common base class or interface they cannot be used in a factory design template.
Uses:
 Factory is used to manipulate objects of same type as abstract objects.
 Whenever an application is designed, factory plays a vital role in creating objects.

STRUCTURAL PATTERNS
Structural patterns are concerned with how classes and objects are composed to form larger
structures. These patterns describe ways to compose objects to realize new functionality.

BRIDGE PATTERN
 Bridge is used, when we need to decouple an abstraction from its implementation so that
the two can vary independently. This type of design pattern comes under structural
pattern as this pattern decouples implementation class and abstract class by providing a
bridge structure between them.

 This pattern involves an interface which acts as a bridge which makes the functionality
of concrete classes independent from interface implementer classes. Both types of
classes can be altered structurally without affecting each other.

 In the following diagram, DrawAPI interface is acting as a bridge implementer and


concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is
an abstract class and will use object of DrawAPI. BridgePatternDemo, a demo class will
use Shape class to draw different colored circle.
ADAPTER PATTERN
Adapter pattern works as a bridge between two incompatible interfaces. It is used to convert the
programming interface of one class into that of another.

Problem
How to resolve incompatible interfaces, or provide a stable interface to similar
components with different interfaces?
Solution:
Convert the original interface of a component into another interface, through an
intermediate adapter object.

Fig: Adapter Pattern


Example:
Consider following example in which an audio player device can play mp3 files only and
wants to use an advanced audio player capable of playing vlc and mp4 files with the use
of adapter.

 In this example, we have a MediaPlayer interface and a concrete class


AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3
format audio files by default.
 We are having another interface AdvancedMediaPlayer and concrete classes
implementing the AdvancedMediaPlayer interface. These classes can play vlc
and mp4 format files.
 We want to make AudioPlayer to play other formats as well. To attain this, we
havecreated an adapter class MediaAdapter which implements the MediaPlayer
interface and uses AdvancedMediaPlayer objects to play the required format.
 AudioPlayer uses the adapter class MediaAdapter passing it to the desired audio type
without knowing the actual class which can play the desired format.
AdapterPatternDemo, a demo class will use AudioPlayer class to play various
formats.
BEHAVIORAL PATTERNS

Behavioral Patterns are concerned with communication between objects. These patterns use
inheritance to distribute behavior between classes.

STRATEGY PATTERN

Problem
How to design for varying, but related, algorithms or policies? How to design for
the ability to change these algorithms or policies?

Solution:
Define each algorithm/policy/strategy in a separate class, with a common interface.
Example:
In this example 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, a demo class, will use Context and strategy objects to demonstrate
change in Context behaviour based on strategy it deploys or uses.

Fig: Strategy Pattern


OBSERVER PATTERN(Publish-Subscribe)

Problem
Different kinds of subscriber objects are interested in state changes or events of a
publisher object,and want to react in their own unique way when the publisher generates an
event. Moreover,the publisher wants to maintain low coupling to the subscribers. What to
do?

Solution:
Define a “subscriber” or “listener” interface. Subscribers implement this interface.
The publisher can dynamically register subscribers who are interested in an event and
notify them when an event occurs.

Fig: The observer SaleFrame1subscribes to the publisher Sale

The SaleFrame1 object is the observer/subscriber/listener. In the above diagram it


subscribes to interest in property events of the Sale, which is a publisher of property
events. The Sale adds the object to its list of PropertyListener subscribers.The Sale does
not know about the SaleFrame1 as a SaleFrame1 object,but only as a PropertyListener
object,this lowers the coupling from the model up to the view layer.
Fig: The Sale publishes a property event to all its subscribers
In the above diagram,when the sale total changes, it iterates across all its registered
subscribers, and “publishes an event” by sending the onPropertyEvent message to each.

You might also like