Sunteți pe pagina 1din 71

BIL 304 Object-Oriented Software Engineering using UML

Chapter 8 Object Design Reuse and Patterns


Eda YCEL

Computer Eng Dept, ukurova University

Computer Eng Dept, ukurova Univ.

E.Ycel

So far...

Analysis:

application objects

We describe the purpose of the system

System design:

off-the-shelf components

We describe the system architecture:


Subsystem decomposition, Global control flow, Persistency management, HW/SW platform, etc.

Object design:

We close the gap between application objects and off-theshelf components the process of adding details to the requirements analysis and making implementation decisions

Object Design

Requirements Analysis: (external behaviour)

Use cases, functional and dynamic model deliver operations for object model

The object designer must choose among different ways to implement the analysis model

with the goal to minimize execution time, memory and other measures of cost. Iterates on the models, in particular the object model and refine the models

Object Design:

Object design serves as the basis of implementation.

System Development as a Set of Activities


System Model

Problem

Application objects

Analysis

Solution objects Custom objects

Design

- Object Design

Off-the-Shelf Components - System Design

Existing Machine

Object Design consists of 4 Activities


1. Reuse: Identification of existing solutions

Use of inheritance Off-the-shelf components and additional solution objects Design patterns Chapter 8 Describes precisely each class interface Chapter 9 Transforms the object design model to improve its understandability and extensibility Chapter 10

2. Interface specification

3. Object model restructuring

4. Object model optimization

Transforms the object design model to address performance criteria such as response time or memory utilization. Chapter 10

Object Design Activities


Select Subsystem

Specification

Reuse

Identifying missing attributes & operations

Identifying components

Specifying visibility Adjusting components Specifying types & signatures Identifying patterns Specifying constraints

Specifying exceptions

Adjusting patterns

Detailed View of Object Design Activities (ctd)


Check Use Cases

Restructuring Revisiting inheritance

Optimization Optimizing access paths

Collapsing classes

Caching complex computations Delaying complex computations

Realizing associations

Identification of new Objects during Object Design


Requirements Analysis (Language of Application Domain)

Incident Report

Text box
Object Design (Language of Solution Domain)

Menu

Scrollbar

Chapter 8: Reuse Concepts


Application objects and Solution objects Specification Inheritance and Implementation Inheritance Delegation Delegation and Inheritance in Design Patterns

Application Domain vs Solution Domain Objects


Application objects: objects from UML Solution objects

have no counterpart in the application domain e.g. persistent data stores, user interface objects, etc.

During analysis, we identify Entity objects, Boundary objects, Control objects:


Entity: application Boundary: solution Control: solution

Modeling of the Real World

Modeling of the real world leads to a system that reflects todays realities but not necessarily tomorrows. There is a need for reusable and flexible designs Design knowledge such as the adapter pattern complements application domain knowledge and solution domain knowledge.

Reuse of Code

I have a list, but my customer would like to have a stack


The list offers the operations Insert(), Find(), Delete() The stack needs the operations Push(), Pop() and Top() Can I reuse the existing list?

I am an employee in a company that builds cars with expensive car stereo systems

Can I reuse the existing car software in a home stero system?

Reuse of existing classes

I have an implementation for a list of elements of Type int

Can I reuse this list to build


a list of customers a spare parts catalog a flight reservation schedule?

I have developed a class Addressbook in another project

Can I add it as a subsystem to my e-mail program which I purchased from a vendor (replacing the vendor-supplied addressbook)? Can I reuse this class in the billing software of my dealer management system?

Customization: Build Custom Objects

Problem: Close the object design gap

Develop new functionality Reuse knowledge from previous experience Reuse functionality already available New functionality is obtained by aggregation The new object with more functionality is an aggregation of existing objects New functionality is obtained by inheritance

Main goal:

Composition (also called Black Box Reuse)


Inheritance (also called White-box Reuse)

Inheritance comes in many Flavors


Inheritance is used in four ways:

Specialization:

identifying a common new subclasses given an existing superclass

Generalization:

identifying a common super class from a number of existing classes


classification of concepts into type hierarchies use of inheritance for the sole purpose of reusing code

Specification Inheritance:

Implementation Inheritance:

Discovering Inheritance

To discover inheritance associations, we can proceed in two ways, which we call specialization and generalization Generalization: the discovery of an inheritance relationship between two classes, where the subclass is discovered first. Specialization: the discovery of an inheritance relationship between two classes, where the super class is discovered first.

Generalization Example: Modeling a Coffee Machine


VendingMachine Generalization: The class CoffeeMachine is discovered first, then the class SodaMachine, then the superclass VendingMachine

CoffeeMachine

SodaMachine totalReceipts cansOfBeer cansOfCola collectMoney() makeChange() chill() dispenseBeverage()

totalReceipts numberOfCups coffeeMix


collectMoney() makeChange() heatWater() dispenseBeverage() addSugar() addCreamer()

After the generalization there is often an opportunity for Restructuring: Why dont we move the methods totalReceipts, collectMoney(), makeChange(), dispenseBeverage() into the super class?

Restructuring of Attributes and Operations is often a Consequence of Generalization


VendingMachine Called Remodeling if done on the model level; Called Refactoring if done on the source code level.
VendingMachine totalReceipts collectMoney() makeChange() dispenseBeverage()

CoffeeMachine totalReceipts numberOfCups coffeeMix collectMoney() makeChange() heatWater() dispenseBeverage() addSugar() addCreamer()

SodaMachine totalReceipts cansOfBeer cansOfCola collectMoney() makeChange() chill() dispenseBeverage()

CoffeeMachine
numberOfCups coffeeMix heatWater() addSugar() addCreamer()

SodaMachine cansOfBeer cansOfCola chill()

An Example of a Specialization
VendingMachine totalReceipts collectMoney() makeChange() dispenseBeverage()
CandyMachine is a new product and designed as a subclass of the superclass VendingMachine A change of names might now be useful: dispenseItem() instead of dispenseBeverage() and dispenseSnack()

CoffeeMachine numberOfCups coffeeMix heatWater() addSugar() addCreamer()

SodaMachine cansOfBeer cansOfCola chill()

CandyMachine bagsofChips numberOfCandyBars dispenseSnack()

Example of a Specialization (2)


VendingMaschine totalReceipts collectMoney() makeChange() dispenseItem() Now we have the method dispenseItem() in the superclass! It should be an abstract method, implemented by each of the subclasses

CoffeeMachine numberOfCups coffeeMix heatWater() addSugar() addCreamer() dispenseItem()

SodaMachine
cansOfBeer cansOfCola chill() dispenseItem()

CandyMachine bagsofChips numberOfCandyBars dispenseItem()

Meta-Model for Inheritance

Inheritance

Analysis activity
Taxonomy Inheritance for Reuse

Object Design

Inheritance detected by specialization

Inheritance detected by generalization

Specification Inheritance

Implementation Inheritance

For Reuse: Implementation Inheritance and Specification Inheritance

Implementation inheritance

Also called class inheritance Goal:


Extend an applications functionality by reusing functionality from the super class Inherit from an existing class with some or all operations already implemented

Specification Inheritance

Also called subtyping Goal:


Inherit from a specification The specification is an abstract class with all operations specified, but not yet implemented.

Example for Implementation Inheritance

A very similar class is already implemented that does almost the same as the desired class implementation List Example:

I have a List class, I need a Stack class How about subclassing the Stack class from the List class and implementing Push(), Pop(), Top() with Add() and Remove()?

Add() Remove()

Already implemented

Push() Pop() Top()

Stack

Problem with implementation inheritance:


The inherited operations might exhibit unwanted behavior. Example: What happens if the Stack user calls Remove() instead of Pop()?

Delegation instead of Implementation Inheritance


Inheritance: Extending a Base class by a new operation or overriding an operation. Delegation: Catching an operation and sending it to another object. Which of the following models is better?
List
+Add() +Remove()

Stack
+Push() +Pop() +Top()

List
Add() Remove()

Stack
+Push() +Pop() +Top()

Delegation Delegation is a way of making composition as powerful for reuse as inheritance In delegation two objects are involved in handling a request from a Client
The Receiver object delegates operations to the

Delegate object

The Receiver object makes sure, that the Client does not

misuse the Delegate object.

Client

calls

Receiver delegates to

Delegate

Design patterns

During Object Modeling we do many transformations and changes to the object model It is important to make sure the object design model stays simple!
Design patterns helps keep system models simple.

Finding Objects

The hardest problems in object-oriented system development are:

Identifying objects Decomposing the system into objects

Requirements Analysis focuses on application domain:

Object identification

System Design addresses both, application and implementation domain:

Subsystem Identification
Additional solution objects

Object Design focuses on implementation domain:

Techniques for Finding Objects

Requirements Analysis

Start with Use Cases. Identify participating objects Textual analysis of flow of events (find nouns, verbs, ...) Extract application domain objects by interviewing client (application domain knowledge) Find objects by using general knowledge Extract objects from Use Case scenarios (dynamic model)

System Design

Subsystem decomposition Try to identify layers and partitions


Find additional objects by applying implementation

Object Design

Another Source for Finding Objects : Design Patterns

What are Design Patterns?


The recurring aspects of designs are called design patterns [Gamma et al 1995]. A pattern is the outline of a reusable solution to a general problem encountered in a particular context. It describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same twice. Many of them have been systematically documented for all software developers to use.

Studying patterns is an effective way to learn from the experience of others

What is common between these definitions?

Definition Software System

A software system consists of subsystems which are either other subsystems or collection of classes

Definition Software Lifecycle:

The software lifecycle consists of a set of development activities which are either other actitivies or collection of tasks

Introducing the Composite Pattern

Models tree structures that represent part-whole hierarchies with arbitrary depth and width. The Composite Pattern lets client treat individual objects and compositions of these objects uniformly
Client Component *

Leaf
Operation()

Composite
Operation() AddComponent RemoveComponent() GetChild()

Children

Modeling a Software System with a Composite Pattern

User

Software System

Class

Subsystem

children

Graphic Applications also use Composite Patterns


The Graphic Class represents both primitives (Line, Circle) and their containers (Picture)
Client Graphic

Line
Draw()

Circle
Draw()

Picture
Draw() Add(Graphic g) RemoveGraphic) GetChild(int)

Children

Reducing the Complexity of Models

To communicate a complex model we use navigation and reduction of complexity


We do not simply use a picture from the CASE tool and dump it in front of the user The key is to navigate through the model so the user can follow it Start with the key abstractions Then decorate the model with additional classes

We start with a very simple model


To reduce the complexity of the model further, we

Look for inheritance (taxonomies)

If the model is still too complex, we show subclasses on a separate slide We make sure to use the name of the patterns.

Then we identify or introduce patterns in the model

Example: A Complex Model


Taxonomies Basic Abstractions
Equipment Project * Resource Facility Fund Organization

Composite Patterns
Schedule * Outcome * produces *

Work Breakdown Structure * consumes

* desWork cribes Package *

* Organizational responWork Unit * sible plays depends for Role Task Participant Staff

Set of Work Products

Work Product

Activity

Internal Work Product

Project Deliverable

Project Function

Department

Team

Inheritance or Delegation

Many design patterns use a combination of inheritance and delegation

Adapter Pattern
Client ClientInterface Request() LegacyClass ExistingRequest()

adaptee Inheritance

Adapter
Request()

Delegation

Adapter behaves as expected by Client The adapter pattern uses inheritance as well as delegation: Interface inheritance is used to specify the interface of the Adapter class. Delegation is used to bind the Adapter and the Adaptee Adapter works with LegacyClass and all its subclasses A new Adapter needs to be written for each specialization

Adapter Pattern

The adapter pattern lets classes work together that couldnt otherwise because of incompatible interfaces

Convert the interface of a class into another interface expected by a client class. Used to provide a new interface to existing legacy components (Interface engineering, reengineering). Class adapter:

Two adapter patterns:


Uses multiple inheritance to adapt one interface to another Uses single inheritance and delegation

Object adapter:

Object adapters are much more frequent. We cover only object adapters (and call them adapters).

Bridge Pattern

Use a bridge to decouple an abstraction from its implementation so that the two can vary independently

Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. Beyond encapsulation, to insulation

Also know as a Handle/Body pattern Allows different implementations of an interface to be decided upon dynamically.

Bridge Pattern

Taxonomy in Application Domain

Taxonomy in Solution Domain

Why the Name Bridge Pattern?

Taxonomy in Application Domain

Taxonomy in Solution Domain

Motivation for the Bridge Pattern

Decouples an abstraction from its implementation so that the two can vary independently This allows to bind one from many different implementations of an interface to a client dynamically Design decision that can be realized any time during the runtime of the system

However, usually the binding occurs at start up time of the system (e.g. in the constructor of the interface class)

Using a Bridge

The bridge pattern can be used to provide multiple implementations under the same interface

Example use of the Bridge Pattern: Support multiple Database Vendors


interface class to the pattern
Arena imp LeagueStore LeagueStoreImplementor

Abstract interface that provides common interface for 3 implementations

Stub Store Implementor

XML Store Implementor

JDBC Store Implementor

Adapter vs Bridge

Similarities:

Both are used to hide the details of the underlying implementation. The adapter pattern is geared towards making unrelated components work together

Difference:

Applied to systems after theyre designed (reengineering, interface engineering). Inheritance followed by delegation

A bridge, on the other hand, is used up-front in a design to let abstractions and implementations vary independently.

Green field engineering of an extensible system New beasts can be added to the object zoo, even if these are not known at analysis or system design time. Delegation followed by inheritance

Facade Pattern

Provides a unified interface to a set of objects in a subsystem. A facade defines a higher-level interface that makes the subsystem easier to use (i.e. it abstracts out the gory details) Facades allow us to provide a closed architecture

Design Example
Subsystem 1

Subsystem 1 can look into the Subsystem 2 (vehicle subsystem) and call on any component or class operation at will. This is Ravioli Design Why is this good?

Subsystem 2 Seat Card

Efficiency Cant expect the caller to understand how the subsystem works or the complex relationships within the subsystem. We can be assured that the subsystem will be misused, leading to non-portable code

Why is this bad?

AIM

SA/RT

Subsystem Design with Faade, Adapter, Bridge

The ideal structure of a subsystem consists of


an interface object a set of application domain objects (entity objects) modeling real entities or existing systems

Some of the application domain objects are interfaces to existing systems

one or more control objects

We can use design patterns to realize this subsystem structure Realization of the Interface Object: Facade

Provides the interface to the subsystem Provides the interface to existing system (legacy system) The existing system is not necessarily object-oriented!

Interface to existing systems: Adapter or Bridge


When should you use these Design Patterns?

A faade should be offered by all subsystems in a software system who provides services

The faade delegates requests to the appropriate components within the subsystem. The faade usually does not have to be changed, when the components are changed

The adapter design pattern should be used to interface to existing components

Example: A smart card software system should use an adapter for a smart card reader from a specific manufacturer

The bridge design pattern should be used to interface to a set of objects


where the full set of objects is not completely known at analysis or design time. when a subsystem or component must be replaced later after the system has been deployed and client programs use it in the field.

Summary

Design patterns are partial solutions to common problems such as


such as separating an interface from a number of alternate implementations wrapping around a set of legacy classes protecting a caller from changes associated with specific platforms uses delegation and inheritance provides a modifiable design solution

A design pattern consists of a small number of classes


These classes can be adapted and refined for the specific system under construction

Customization of the system Reuse of existing solutions.

A Taxonomy of Design Patterns

The Proxy Pattern: 3 Types

Caching of information (Remote Proxy)


The Proxy object is a local representative for an object in a different address space Good if information does not change too often Object is too expensive to create or too expensive to download. Good if the real object is not accessed too often

Standin (Virtual Proxy)

Example: RealImage and ImageProxy

Access control (Protection Proxy)

The proxy object provides protection for the real object Good when different actors should have different access and viewing rights for the same object

Example: Grade information accessed by administrators, teachers and students.

Command Pattern: Motivation


You want to build a user interface You want to provide menus You want to make the menus reusable across many applications

The applications only know what has to be done when a command from the menu is selected You dont want to hardcode the menu commands for the various applications

Such a user interface can easily be implemented with the Command Pattern.

Decouples boundary objects from control objects

The command pattern can be nicely used to decouple boundary objects from control objects:

Boundary objects such as menu items and buttons, send messages to the command objects (I.e. the control objects) Only the command objects modify entity objects

When the user interface is changed (for example, a menu bar is replaced by a tool bar), only the boundary objects are modified. Command pattern is often used in a Model/View/Controller software architecture.

Command Pattern Applicability

Encapsulate a request as an object, thereby letting you


parameterize clients with different requests queue or log requests support undoable operations

Uses:

Undo queues Database transaction buffering

Applying the Command Pattern to Command Sets


We want to record individual moves in matches so that these moves can be replayed by a spectator at a later date We want ARENA to support a broad spectrum of games
Match play() replay()
* Move execute()

binds GameBoard TicTacToeMove execute() ChessMove execute()

Observer Pattern Motivation

Portfolio * Stock

Problem:

We have an object that changes its state quite often

Example: A Portfolio of stocks

We want to provide multiple views of the current state of the portfolio

Example:Histogram view, pie chart view, time line view, alarm

Requirements:

The system should maintain consistency across the (redundant) views, whenever the state of the observed object changes The system design should be highly extensible

It should be possible to add new views without having

Observer Pattern: Decouples an Abstraction from its Views


Subject
observers
subscribe(subscriber) unsubscribe(subscriber) notify()

Observer
*
update()

ConcreteSubject
state getState() setState()

ConcreteObserver
observeState
update()

The Subject (Publisher) represents the entity object Observers (Subscribers) attach to the Subject by calling subscribe() Each Observer has a different view of the state of the entity object
The state is contained in the subclass ConcreteSubject The state can be obtained and set by subclasses of type ConcreteObserver.

Observer Pattern

Models a 1-to-many dependency between objects

Connects the state of an observed object, the subject with many observing objects, the observers Maintaining consistency across redundant states Optimizing a batch of changes to maintain consistency Push Notification: Every time the state of the subject changes, all the observers are notified of the change

Usage:

Three variants for maintaining the consistency:

Push-Update Notification: The subject also sends the state that has been changed to the observers

Pull Notification: An observer inquires about the state the of the subject

Also called Publish and Subscribe.

Applying the Observer Pattern to maintain Consistency across Views


Subject subscribe() unsubscribe() notify() * Observer update()

File -filename getState() setState()

InfoView update() ListView update() PowerpointView update()

Strategy Pattern

Different algorithms exists for a specific task

We can switch between the algorithms at run time Different collision strategies for objects in video games Parsing a set of tokens into an abstract syntax tree (Bottom up, top down) Sorting a list of customers (Bubble sort, mergesort, quicksort)

Examples of tasks:

Different algorithms will be appropriate at different times

First build, testing the system, delivering the final product

If we need a new algorithm, we can add it without disturbing the application or the other algorithms.

Strategy Pattern
Policy

Context
ContextInterface()

Strategy
AlgorithmInterface

ConcreteStrategyA
AlgorithmInterface()

ConcreteStrategyB
AlgorithmInterface()

ConcreteStrategyC
AlgorithmInterface()

Policy decides which ConcreteStrategy is best in the current Context.

Using a Strategy Pattern to Decide between Algorithms at Runtime


Client Policy TimeIsImportant SpaceIsImportant

Database SelectSortAlgorithm() Sort() *

SortInterface

Sort()

BubbleSort
Sort() Sort()

QuickSort
Sort()

MergeSort

Abstract Factory Pattern Motivation

Consider a user interface toolkit that supports multiple looks and feel standards for different operating systems:

How can you write a single user interface and make it portable across the different look and feel standards for these window managers?

Consider a facility management system for an intelligent house that supports different control systems:

How can you write a single control system that is independent from the manufacturer?

Abstract Factory
AbstractFactory Client CreateProductA CreateProductB ProductA1 ProductA2 AbstractProductA

ConcreteFactory1

AbstractProductB

CreateProductA CreateProductB
ProductB1 ConcreteFactory2 CreateProductA CreateProductB ProductB2

Initiation Assocation: Class ConcreteFactory2 initiates the associated classes ProductB2 and ProductA2

Applicability for Abstract Factory Pattern


Independence from Initialization or Representation Manufacturer Independence Constraints on related products Cope with upcoming change

Applying the Abstract Factory Pattern to Games


Tournament Game createMatch() createStatistics()

TicTacToe createMatch() createStats()

Chess createMatch() createStats()

Match

Statistics

TTTMatch

ChessMatch

TTTStats

ChessStats

Clues in Nonfunctional Requirements for the Use of Design Patterns

Text: manufacturer independent, device independent, must support a family of products


=> Abstract Factory Pattern

Text: must interface with an existing object


=> Adapter Pattern

Text: must interface to several systems, some of them to be developed in the future, an early prototype must be demonstrated
=>Bridge Pattern

Text: must interface to existing set of objects


=> Faade Pattern

Clues in Nonfunctional Requirements for use of Design Patterns (2)

Text: complex structure, must have variable depth and width


=> Composite Pattern

Text: must be location transparent


=> Proxy Pattern

Text: must be extensible, must be scalable


=> Observer Pattern

Text: must provide a policy independent from the mechanism


=> Strategy Pattern

Summary

Composite, Adapter, Bridge, Faade, Proxy (Structural Patterns)

Focus: Composing objects to form larger structures


Realize new functionality from old functionality, Provide flexibility and extensibility

Command, Observer, Strategy, Template (Behavioral Patterns)

Focus: Algorithms and assignment of responsibilities to objects

Avoid tight coupling to a particular solution

Abstract Factory, Builder (Creational Patterns)

Focus: Creation of complex objects

Hide how complex objects are created and put together

Conclusion
Design patterns

provide solutions to common problems lead to extensible models and code can be used as is or as examples of interface inheritance and delegation apply the same principles to structure and to behavior

Design patterns solve a lot of your software development problems

Pattern-oriented development

S-ar putea să vă placă și