Вы находитесь на странице: 1из 36

RDD

and Strategy Pa.ern

1 CSCI 3132 Summer 2011

OO So1ware Design
The tradi7onal view of objects is that they are data with methods. Smart Data. But, it is be.er to think of them as en##es that have responsibili#es. This helps us focus on what objects are supposed to do, so we can hide the implementa7on details. so we can focus on an objects public interface. so we do not need to know what is going on inside the object. This enables you to delegate responsibility.
2

RDD

A popular way of thinking about the design of software objects and also larger-scale components is in terms of responsibilities roles, and collaborations. This is part of a larger approach called Responsibility-Driven Design or RDD

Basically, these responsibilities are of the following two types: - Doing - Knowing.
3

RDD

Doing responsibilities of an object include: doing something itself, such as creating an object or doing a calculation initiating action in other objects controlling and coordinating activities in other objects Knowing responsibilities of an object include: knowing about private encapsulated data knowing about related objects knowing about things it can derive or calculate Think of software objects as similar to people with responsibilities who collaborate with other people to get work done. 4

Example
What responsibili7es does a Shape have? To know where it is located. To be able to draw itself on a display. To be able to remove itself from a display. This implies three methods: getLocation() drawShape() unDrawShape() We do not need to know anything about the inner workings of the Shape class, like a.ributes or another object. Focus on mo7va7on rather than implementa7on.
5

Loose Coupling
Hiding the implementa7on of Shape behind interfaces essen7ally decouples them from the using objects. Deni7on: Two modules are coupled if they depend on each other in any way. Decoupling is the key to good design. It means that if something changes on the other side of the interface, the non-changed side should not require altera7on.

High Cohesion
. Definition: The degree to which all elements of a component are directed towards a single task and all elements directed towards that task are contained in a single component.

Rule of thumb: a class with high cohesion has - a relatively small number of methods, with highly related functionality, - and does not do too much work. High is better, so the code is relatively easy to maintain, understand, and reuse.
7

Coupling and Cohesion


Our goals: Loose coupling: Allow unrelated things in the code to change independently (also known as orthogonality). High cohesion: Keep things that have to change together as close together in the code as possible. Minimize duplica7on in the code.
8

Encapsula7on
Tradi7onal view of encapsula7on: data hiding. Encapsula7on isnt just data hiding. Encapsula7on is any kind of hiding. You can hide: Implementa7ons Derived Classes Design Details

Encapsula7on in a Boarder View


The Adapter pa.ern example shows many kinds of encapsula7on. Can you name them?

10

Inheritance Revisit
Imagine you have a class called Pentagon to contain state, draw, undraw, and so on. Later you decide you also want a special Pentagon with a special border. We can create a Pentagon with a special border class that is derived from Pentagon.

11

Problems
Problems of Using Inheritance for Specializa7on: Weak Cohesion: What happens if we have lots of borders? If each border is a separate class then related code is being divided up. Reduces reuse: What happens if I want to reuse the special border for other shapes? This solu7on does not allow that to occur. Doesnt scale well with varia#on: What happens if other things vary? Two dierent kinds of shading and much more? Need to specialize the Pentagon class repeatedly.

12

A Be.er Approach
Consider what should be variable in your design (not always easy) and encapsulate it. Use inheritance to classify varia7ons in behaviours. Thus, the using class can have a reference to an abstract class or interface that has more than one specialized deriva7on. These deriva7ons are encapsulated from the using class. E.g. Add a reference to a Border abstract class.

13

Another Example
Consider the tradi7onal problem of crea7ng classes that represent animals. Your requirements are: Animal objects must be able to keep and retrieve this informa7on Each type of animal can have a dierent number of legs Each type of animal can have a dierent type of movement A traditional approach: - Have data member containing the number of legs and its setter and getter method. - Create a inheritance hierarchy: start with animal, then have mammals, reptiles, etc. and keep creating more and more specific animals till you have all species.
14

A Be.er Solu7on
Works with many varia7ons are present. It is be.er to have a data member that indicates the type of movement the object has.

15

Design For Change


We do not an7cipate the exact change, instead we an7cipate what may change. A Case Study: E-Commerce System The company is located in the US, but its business has an interna7onal scope A Task controller object handles sales request and passes it to the SalesOrder object to process the order.

16

Case Study: E-commerce System


The func7ons for SalesOrder include the following: Allow for lling out the order with a GUI Handle tax calcula7ons Process the order and print a sales receipt What happens when requirements change? Perhaps a new requirement for taxa7on rules is added to handle tax in Canada. Thus, we need to add new rules for compu7ng taxes.
17

Handle Varia7on with Switches


// Handle Tax switch (myNation) { case US: //US Tax Rules here break; case Canada: //Canadian Tax Rules here break; } //Handle Currency switch (myNation) { case US: //US Currency Rules here break; case Canada: //Canadian Currency Rules here break; }

18

Handle Varia7on with Switches


//Handle Date Format switch (myNation) { case US: //US Date Format Rules here break; case Canada: //Canadian Date Format Rules here break; }

Switches Issues with coupling, testing More importantly, what happens when you have multiple variations?
19

Handle Varia7on
Add a Third Country S7ll a Clean implementa7on, need another switch
// Handle Tax switch (myNation) { case US: //US Tax Rules here break; case Canada: //Canadian Tax Rules here break; case Germany: //Germany Tax Rules here break; }

20

//Handle Currency switch (myNation) { case US: //US Currency Rules here break; case Canada: //Canadian Currency Rules here break; case Germany: //Germany Currency Rules here break; } // Handle Language switch (myNation) { case US: case Canada: //use English break; case Germany: //use German break; }

21

Handle More Varia7ons


Varia7ons dirty the implementa7on
// Handle Language switch (myNation) { case Canada: if (inQuebec) { //use French break;} else //use English break; case Germany: //use German break; }

Flow of the switches is hard to read When new cases come in, you must nd every place it can be involved. This is called Switch Creep
22

Another Approach
Inheritance Nothing really wrong with it per say Certainly allows reuse Could create new SalesOrder objects from exis7ng objects But, can it handle all the varia7ons easily? With tall inheritance hierarchies?

23

A Be.er Approach
1. Find out what varies and encapsulate it in a class of its own. 2. Contain this class in another class. What varies in this example? Tax rules, therefore create an abstract class that denes how to accomplish taxa7on conceptually.

24

Favor Object-aggrega7on over Inheritance


Now use aggrega7on to give the SalesOrder object the ability to handle Tax.

25

Use of Congura7on File

26

S7ll with Inheritance, but used dierently


So Whats the Dierence? Looking at it quickly, it appears we just pushed the problem down the chain. The key dierence is that in the original solu7on, there was one large hierarchy containing all the varia7on. The improved solu7on has a few, smaller, independent hierarchies. Other pieces of the system can use the smaller object hierarchies we created.
27

The Strategy Pa.ern


Intent: (GoF) Dene a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. The Strategy Pa.ern is based on a few principles: Objects have responsibili7es Dierent specic implementa7ons of these responsibili7es are manifested through the use of polymorphism There is a need to manage several dierent implementa7ons of the same basic algorithm. It is good design prac7ce to separate behaviors that occur in the same problem domain from each other.
28

Strategy Pa.ern
Intent: Enable you to use dierent business rules or algorithms depending on the context in which they occur. Problem: The selec7on of an algorithm that needs to be applied depends on the client making the request or the data being acted on. Solu#on: Separate the selec7on of the algorithm from the implementa7on of the algorithm.

29

The Strategy Pa.ern


Par#cipants and collaborators Strategy species how the dierent algorithms are used. ConcreteStrategies implement these dierent algorithms. Context uses a specic ConcreteStrategies with a reference of type Strategy. Strategy and Context interact to implement the chosen algorithm. The Context forwards request form its client to Strategy.

30

Strategy Pa.ern
Consequences:
Families of related algorithms. An alterna7ve to subclassing. Strategies eliminate condi7onal statements. A choice of implementa7ons. Clients must be aware of dierent strategies. Communica7on overhead between Strategy and Context. Increased number of objects.

31

Strategy Pa.ern
Implementa#on: Have the class that uses the algorithm (Context) contain an abstract class (Strategy) that has an abstract method specifying how to call the algorithm. Each derived class implements the algorithm needed.

32

An Example : Sort
Assume that, you need to write a sort program that will have an array and at run-7me you want to decide which sort algorithm to use. Strategy is what we group the many algorithms that do the same things and make it interchangeable at run- 7me
Bubble Runtime Sort
Ascending Sort

SortStrategies
Selec#on Sort

Descending Sort

Quick Sort

Input #1 #2 Heap

Sort

Result #1 #2

33

Class Diagram of Sort Example

34

Another Example
Many dierent layout strategies exist. A GUI container wants to decide at run-7me which layout to use. Encapsulate each dierent layout algorithm using the strategy pa.ern.

35

Class Diagram of Layout Example

36

Вам также может понравиться