Chapter 8 Object Design: Reuse and Patterns.

Slides:



Advertisements
Similar presentations
Chapter 8, Object Design: Design Patterns II Using UML, Patterns, and Java Object-Oriented Software Engineering.
Advertisements

Design Patterns CS is not simply about programming
Chapter 8, Object Design Introduction to Design Patterns
Design Patterns Based on Design Patterns. Elements of Reusable Object-Oriented Software. by E.Gamma, R. Helm, R. Johnson,J. Vlissides.
Chapter 8 Object Design Reuse and Patterns. Finding Objects The hardest problems in object-oriented system development are: –Identifying objects –Decomposing.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Reuse Activities Selecting Design Patterns and Components
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
Design Patterns academy.zariba.com 1. Lecture Content 1.What are Design Patterns? 2.Creational 3.Structural 4.Behavioral 5.Architectural 6.Design Patterns.
1 An introduction to design patterns Based on material produced by John Vlissides and Douglas C. Schmidt.
Design Patterns.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Bernd Bruegge & Allen H. Dutoit Object-Oriented Software Engineering: Using UML, Patterns, and Java 1 Outline of the Lecture  Patterns covered  Composite:
Proxy Pattern: Motivation
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
Chapter 8 Object Design Reuse and Patterns. Object Design Object design is the process of adding details to the requirements analysis and making implementation.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Structural Design Patterns
ECE450S – Software Engineering II
Using UML, Patterns, and Java Object-Oriented Software Engineering Chapter 8, Object Design: Introduction to Design Patterns.
08 - StructuralCSC4071 Structural Patterns concerned with how classes and objects are composed to form larger structures –Adapter interface converter Bridge.
Structural Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
Chapter 8 Object Design Reuse and Patterns. More Patterns Abstract Factory: Provide manufacturer independence Builder: Hide a complex creation process.
CS 5150 Software Engineering Lecture 16 Program Design 3.
Five Minute Design Patterns Doug Marttila Forest and the Trees May 30, 2009 Template Factory Singleton Iterator Adapter Façade Observer Command Strategy.
COP 3331 Object-Oriented Analysis and Design 1 Design Overview  Design Overview (Ch 6)  Review of RAD  System Design  System Design Concepts  System.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Examples (D. Schmidt et al)
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Chapter 8 Object Design: Reuse and Patterns.
Chapter 8 Object Design: Reuse and Patterns 2.
Design Patterns: MORE Examples
Abstract Factory Pattern
Design Patterns: Brief Examples
Object Design II: Design Patterns
Chapter 8, Object Design: Reuse and Patterns III
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
Chapter 8, Object Design Introduction to Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Behavioral Design Patterns
Instructor: Dr. Hany H. Ammar
Chapter 8 Object Design: Reuse and Patterns 2.
Facade Pattern Jim Fawcett CSE776 – Design Patterns Summer 2010
Chapter 8, Object Design Reuse and Patterns II
object oriented Principles of software design
Abstract Factory Pattern
Chapter 6, System Design Design Patterns
Presented by Igor Ivković
Chapter 8, Object Design Introduction to Design Patterns
Informatics 122 Software Design II
Informatics 122 Software Design II
Chapter 8, Design Patterns Introduction
Presented by Igor Ivković
Adapter Pattern Jim Fawcett
Chapter 8, DesignPatterns Facade
Adapter Pattern Jim Fawcett
Presentation transcript:

Chapter 8 Object Design: Reuse and Patterns

Interface inheritance All subclasses respond to the requests in the interface of this abstract class, making them all subtype of the abstract class Benefit: Clients remain unaware of the class that implement the type of object. Clients only know about the abstract class defining the interface. Reduce implementation dependencies between subsystems Software Reuse -- Program to an interface, not an implementation.

Some rules Program to an interface, not an implementation. Favor object composition over class inheritance Interface inheritance + delegation  reuse design pattern

What are Design Patterns? A design pattern describes a problem which occurs over and over again in our environment Then it describes the core of the solution to that problem, in such a way that you can use the solution a million times over, without ever doing it the same twice

Towards a Pattern Taxonomy Structural Patterns Adapters, Bridges, Facades, and Proxies are variations on a single theme: They reduce the coupling between two or more classes They introduce an abstract class to enable future extensions They encapsulate complex structures Behavioral Patterns Here we are concerned with algorithms and the assignment of responsibilies between objects: Who does what? Behavorial patterns allow us to characterize complex control flows that are difficult to follow at runtime. Creational Patterns Here we our goal is to provide a simple abstraction for a complex instantiation process. We want to make the system independent from the way its objects are created, composed and represented.

A Pattern Taxonomy Pattern Structural Behavioral Creational Abstract Factory Builder Pattern Adapter Bridge Facade Proxy Command Observer Strategy Composite

Design patterns Creational Structural Behavioral Adapter Bridge Abstract Factory Builder Prototype Singleton etc. Adapter Bridge Composite Decorator Façade Proxy Command Iterator Observer Strategy Interpreter Mediator

The Composite Design pattern

What is common between these definitions? Definition of Software System A software system consists of subsystems which are either other subsystems or collection of classes Definition of Software Lifecycle: The software lifecycle consists of a set of development activities which are either other activities 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

What is common between these definitions? Software System: Definition: A software system consists of subsystems which are either other subsystems or collection of classes Composite: Subsystem (A software system consists of subsystems which consists of subsystems , which consists of subsystems, which...) Leaf node: Class Software Lifecycle: Definition: The software lifecycle consists of a set of development activities which are either other actitivies or collection of tasks Composite: Activity (The software lifecycle consists of activities which consist of activities, which consist of activities, which....) Leaf node: Task

Modeling a Software System with a Composite Pattern User Software System * Class Subsystem Children

Modeling the Software Lifecycle with a Composite Pattern Manager Software Lifecycle * Task Activity Children

The Composite Patterns models dynamic aggregates Fixed Structure: Car * * Battery Engine Doors Wheels Organization Chart (variable aggregate): * School * What you are seeing on this slide are what I would like to call patterns for analysis. A pattern is a recurring theme, something once you get used to see something this way, allows you to very fast understand a situation. It is well known, that if you show a set of chess positions of middle games tochess masters and non chess players, that chess masters are able to reconstruct these games without any effort. However, if you give them random chess configurations, chess masters are about as bad as non-chess players in reconstructing the boards. This tells you about the value of patterns. I would like you to learn about these aggregation patterns. In fact, I challenge you to see for your team and subsystem, if any of the analysis problems you face, can be cast in terms of one of the 3 patterns above. University Department Dynamic tree (recursive aggregate): Composite Pattern Dynamic tree (recursive aggregate): Program * * Block Compound Simple Statement Statement

Graphic Applications also use Composite Patterns The Graphic Class represents both primitives (Line, Circle) and their containers (Picture) Client Graphic Circle Draw() Picture Add(Graphic g) RemoveGraphic) GetChild(int) Children Line Question: How to implement the Draw() of the Picture?

Design Patterns reduce 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 navigate through the model so the user can follow it. We start with a very simple model and then decorate it incrementally Start with key abstractions (use animation) Then decorate the model with the additional classes To reduce the complexity of the model even further, we Apply the use of inheritance (for taxonomies, and for design patterns) If the model is still too complex, we show the subclasses on a separate slide Then identify (or introduced) patterns in the model We make sure to use the name of the patterns

Example: A More Complex Model of a Software Project Basic Abstractions Taxonomies Composite Patterns This model is already much more complex than the model shown on the previous slide. Its purpose is still for communication only. Because it already has quite a number of abstractions, It can only be understood if we communicate the model well to the user. We can do this by navigating through the model and highlight basic abstractions and typical patterns. For example, we can highlight the basic abstraction (the ones used in the previous slide) <<Proceed to first animation>> and tell the listener that these are the abstraction used in the previous slide (to make the point more clear, the instructor can move once more to the previous slide) To reduce the complexity of the model, the instructor can then point out that Work Product, Task and Participant all are now basic leaves in a composite pattern. <<Proceed to the next animation, show the use of the composite patterns>>. To reduce the complexity even further, the instructor finally points out the use of inheritance for the taxonomies (Resource, Staff, Work Product and Activity) Given these three tips, the students should be able to understand the model themselves.

Exercise Redraw the complete model for Project from your memory using the following knowledge The key abstractions are workproduct, task, schedule, and participant Workproduct, Task and Participant are modeled with composite patterns, for example There are taxonomies for each of the key abstractions You have 5 minutes! Work Product *

Java‘s AWT library can be modeled with the composite pattern Graphics Component Button TextField Label * TextArea Text Container add(Component c) paint(Graphics g) getGraphics()

The Adapter Design pattern USB AC Adapter Let’s draw a class diagram!

Problem 1 TextView getExtent() Shape Line PolygonShape DrawingEditor BoundingBox() Createmanipulator() Line PolygonShape DrawingEditor text TextShape BoundingBox() Createmanipulator() Return text.getExtent() Class Adapter – Multiple inheritance Return new TextManipulator Another way?

Problem 1 TextView getExtent() Shape Line PolygonShape DrawingEditor BoundingBox() Createmanipulator() Line PolygonShape DrawingEditor TextShape BoundingBox() Createmanipulator() Return getExtent() Return new TextManipulator

Adapter Pattern “Convert the interface of a class into another interface clients expect.” The adapter pattern lets classes work together that couldn’t otherwise because of incompatible interfaces Used to provide a new interface to existing legacy components (Interface engineering, reengineering). Also known as a wrapper

Adapter Pattern Delegation is used to bind an Adapter and an Adaptee Client Target Request() Adaptee ExistingRequest() Adapter Request() adaptee Delegation is used to bind an Adapter and an Adaptee Interface inheritance is use to specify the interface of the Adapter class. Target and Adaptee (usually called legacy system) pre-exist the Adapter. Target may be realized as an interface in Java.

Adapter pattern An example on textbook P320 Question: Why does Array need to interact with Comparator, which is an abstract class?

The Facade Design pattern

Design Example Subsystem 1 can look into the Subsystem 2 (vehicle subsystem) and call on any component or class operation at will. Why is this good? Efficiency Why is this bad? Can’t 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 Subsystem 1 Subsystem 2 Seat Card AIM SA/RT A better design?

Realizing an Opaque Architecture with a Facade VIP Subsystem The subsystem decides exactly how it is accessed. No need to worry about misuse by callers If a façade is used the subsystem can be used in an early integration test We need to write only a driver Vehicle Subsystem API Card Seat AIM SA/RT

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 Note that the Façade class is not a abstract class.

Subsystem Design using Façade, Adapter 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 Interface to existing systems: Adapter Provides the interface to existing system (legacy system) The existing system is not necessarily object-oriented!

Question: Compare the Adapter design pattern and the Façade design pattern.

The Strategy Design pattern

Problem Many different algorithms exists for the same task Examples: Breaking a stream of text into lines Parsing a set of tokens into an abstract syntax tree Sorting a list of customers The different algorithms will be appropriate at different times Rapid prototyping vs delivery of final product We don’t want to support all the algorithms if we don’t need them If we need a new algorithm, we want to add it easily without disturbing the application using the algorithm To summarize: We want to be able to dynamically switch among different algorithms We want to support extensibility to incorporate new algorithms

Composition&Compositor Problem Maintain and update the linebreaks of text displayed in a test viewer using a linebreaking algorithm. Composition&Compositor A big and hard-to-maintain client Composition Compositor Maintain and update linebreaks Linebreaking algorithms ?

Strategy pattern Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Also known as Policy

Applicability of Strategy Pattern Many related classes differ only in their behavior. Strategy allows to configure a single class with one of many behaviors Different variants of an algorithm are needed that trade-off space against time. All these variants can be implemented as a class hierarchy of algorithms

AlgorithmInterface() AlgorithmInterface() AlgorithmInterface() Structure Policy Context ContextInterface() * Strategy AlgorithmInterface ConcreteStrategyC AlgorithmInterface() ConcreteStrategyA AlgorithmInterface() ConcreteStrategyB AlgorithmInterface() Policy decides which Strategy is best given the current Context

Applying a Strategy Pattern in a Database Application Search() Sort() * Strategy Strategy Sort() BubbleSort Sort() QuickSort Sort() MergeSort Sort()

Sample code P. 323

The NetworkConnection Example – P. 322 Send() Receive() setNetworkInterface() * Strategy NetworkInterface Open(),close(), send(), receive() LocationManager Ethernet Open(), close(), send(), receive() WaveLan open(), close(), send(), receive() UMTS open(), close(), send(), receive()

The Proxy Design pattern

Proxy Pattern: Motivation It is 15:00pm. I am sitting at my 14.4 baud modem connection and retrieve a fancy web site from the US, This is prime web time all over the US. So I am getting 10 bits/sec. What can I do?

Proxy Pattern What is expensive? Object Creation Object Initialization Defer object creation and object initialization to the time you need the object Proxy pattern: Reduces the cost of accessing objects Uses another object (“the proxy”) that acts as a stand-in for the real object The proxy creates the real object only if the user asks for it

Before

Controlling Access

After

Virtual Proxy example Image boundingBox() draw() Client ProxyImage boundingBox() draw() RealImage boundingBox() draw() realSubject Images are stored and loaded separately from text If a RealImage is not loaded a ProxyImage displays a grey rectangle in place of the image The client cannot tell that it is dealing with a ProxyImage instead of a RealImage

Proxy pattern Subject Request() RealSubject Proxy realSubject Interface inheritance is used to specify the interface shared by Proxy and RealSubject. Delegation is used to catch and forward any accesses to the RealSubject (if desired) Proxy patterns can be used for lazy evaluation and for remote invocation. Proxy patterns can be implemented with a Java interface.

Proxy Applicability Remote Proxy Virtual Proxy Local representative for an object in a different address space Caching of information: Good if information does not change too often Virtual Proxy Object is too expensive to create or too expensive to download Proxy is a standin Protection Proxy (Security Proxy) Proxy provides access control to the real object Useful when different objects should have different access and viewing rights for the same document. Example: Grade information for a student shared by administrators, teachers and students.

Design Patterns encourage reusable Designs A facade pattern should be used by all subsystems in a software system. The façade defines all the services of the subsystem. The facade will delegate requests to the appropriate components within the subsystem. Most of the time the façade does not need to be changed, when the component is changed, Adapters should be used to interface two existing components. For example, a smart card software system should provide an adapter for a particular smart card reader and other hardware that it controls and queries. Model/View/Controller should be used when the interface changes much more rapidly than the application domain.

Summary: two general rules in design patterns Program to an interface, not an implementation. Favor object composition over class inheritance Interface inheritance + delegation  reuse design pattern

Summary Design patterns are partial solutions to common problems 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. A design pattern is composed of a small number of classes use delegation and inheritance provide a robust and modifiable solution. These classes can be adapted and refined for the specific system under construction. Customization of the system Reuse of existing solutions

Summary II Composite Pattern: Facade Pattern: Adapter Pattern: Models trees with dynamic width and dynamic depth Facade Pattern: Interface to a subsystem closed vs open architecture Adapter Pattern: Interface to reality Strategy Pattern: Family of related algorithms Proxy Pattern: Uses the proxy to act as a stand-in for the real object

Reuse in Object Design Select existing off-the-shelf class libraries frameworks or components code Adjust the class libraries, framework or components Change the API if you have the source code. Use the adapter or bridge pattern if you don’t have access Architecture Driven Design

Reuse... Look for existing classes in class libraries JSAPI, JTAPI, .... Select data structures appropriate to the algorithms Container classes Arrays, lists, queues, stacks, sets, trees, ... It might be necessary to define new internal classes and operations Complex operations defined in terms of lower-level operations might need new classes and operations

Frameworks A framework is a reusable partial application that can be specialized to produce custom applications. Frameworks are targeted to particular technologies, such as data processing or cellular communications, or to application domains, such as user interfaces or real-time avionics. The key benefits of frameworks are reusability and extensibility. Reusability leverages of the application domain knowledge and prior effort of experienced developers Extensibility is provided by hook methods, which are overwritten by the application to extend the framework. Hook methods systematically decouple the interfaces and behaviors of an application domain from the variations required by an application in a particular context.

Frameworks in the Development Process Infrastructure frameworks aim to simplify the software development process System infrastructure frameworks are used internally within a software project and are usually not delivered to a client. Middleware frameworks are used to integrate existing distributed applications and components. Examples: MFC, DCOM, Java RMI, WebObjects, WebSphere, WebLogic Enterprise Application [BEA]. Enterprise application frameworks are application specific and focus on domains Example domains: telecommunications, avionics, environmental modeling, manufacturing, financial engineering, enterprise business activities.

Class libraries and Frameworks Less domain specific Provide a smaller scope of reuse. Class libraries are passive; no constraint on control flow. Framework: Classes cooperate for a family of related applications. Frameworks are active; affect the flow of control. In practice, developers often use both: Frameworks often use class libraries internally to simplify the development of the framework. Framework event handlers use class libraries to perform basic tasks (e.g. string processing, file management, numerical analysis…. )

Components and Frameworks Self-contained instances of classes Plugged together to form complete applications. Blackbox that defines a cohesive set of operations, Can be used based on the syntax and semantics of the interface. Components can even be reused on the binary code level. The advantage is that applications do not always have to be recompiled when components change. Frameworks: Often used to develop components Components are often plugged into blackbox frameworks.

Example: Framework for Building Web Applications WebObjects WebBrowser StaticHTML WOAdaptor WebServer WoRequest Template WebObjectsApplication WORequest EOF RelationalDatabase