Informatics 122 Software Design II

Slides:



Advertisements
Similar presentations
Welcome to. Who am I? A better way to code Design Patterns ???  What are design patterns?  How many are there?  How do I use them?  When do I use.
Advertisements

Winter 2007ACS-3913 Ron McFadyen1 Duck Example Consider the text example (up to page 6). Each type of duck is a subclass of Duck Most subclasses implement.
+ Informatics 122 Software Design II Lecture 7 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
(c) 2009 University of California, Irvine – André van der Hoek1June 13, 2015 – 21:42:16 Informatics 122 Software Design II Lecture 8 André van der Hoek.
Design Patterns CS is not simply about programming
Design Patterns. What are design patterns? A general reusable solution to a commonly occurring problem. A description or template for how to solve a problem.
DESIGN PATTERNS Redesigning Applications And
Dept. of Computer Engineering, Amir-Kabir University 1 Design Patterns Dr. Noorhosseini Lecture 2.
(c) 2010 University of California, Irvine – André van der Hoek1June 29, 2015 – 08:55:05 Informatics 122 Software Design II Lecture 8 André van der Hoek.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Design Patterns: someone has already.
Spring 2010ACS-3913 Ron McFadyen1 Duck Example Consider the text example (up to page 6). Each type of duck is a subclass of Duck Most subclasses implement.
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
(c) 2010 University of California, Irvine – André van der Hoek1July 16, 2015 – 13:45:31 Informatics 122 Software Design II Lecture 8 Nick Lopez Duplication.
+ Informatics 122 Software Design II Lecture 8 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Vrije Universiteit amsterdamPostacademische Cursus Informatie Technologie Idioms and Patterns polymorphism -- inheritance and delegation idioms -- realizing.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
Design Patterns.
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
05 - Patterns Intro.CSC4071 Design Patterns Designing good and reusable OO software is hard. –Mix of specific + general –Impossible to get it right the.
CSSE 374: Introduction to Gang of Four Design Patterns
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
Creational Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Design Patterns in Java Chapter 1 Introduction Summary prepared by Kirk Scott 1.
Design Patterns CSCI 5801: Software Engineering. Design Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IX Interpreter, Mediator, Template Method recap.
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
L11-12: Design Patterns Definition Iterator (L4: Inheritance)‏ Factory (L4: Inheritance)‏ Strategy (L5: Multiple Inheritance)‏ Composite (L6: Implementation.
Software Design Patterns (1) Introduction. patterns do … & do not … Patterns do... provide common vocabulary provide “shorthand” for effectively communicating.
CS 210 Adapter Pattern October 19 th, Adapters in real life Page 236 – Head First Design Patterns.
CSE 403 Lecture 14 Design Patterns. Today’s educational objective Understand the basics of design patterns Be able to distinguish them from design approaches.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
ECE450S – Software Engineering II
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
SE-2811 Software Component Design Week 1, Day 2 (and 1-3 and 2-1) SE-2811 Dr. Josiah Yoder Slide style: Dr. Hornick 1.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Software Design Patterns Curtsy: Fahad Hassan (TxLabs)
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Design Patterns. 1 Paradigm4 Concepts 9 Principles23 Patterns.
Design Patterns Introduction
BEHAVIORAL PATTERNS 13-Sep-2012 Presenters Sanjeeb Kumar Nanda & Shankar Gogada.
Design Patterns Introduction “Patterns are discovered, not invented” Richard Helm.
CS 210 Introduction to Design Patterns August 29, 2006.
It started with a simple … A highly successful duck pond simulation game called SimUDuck The game can show a large variety of duck swimming and making.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
SE 461 Software Patterns Welcome to Design Patterns.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
Software Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Behavioral Design Patterns
object oriented Principles of software design
Strategy Design Pattern
SE-2811 Software Component Design
Informatics 122 Software Design II
SE-2811 Software Component Design
Structural Patterns: Adapter and Bridge
Informatics 122 Software Design II
Chapter 8, Design Patterns Introduction
Presentation transcript:

Informatics 122 Software Design II Lecture 4 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission of the professor is prohibited. Portions of the slides in this lecture are adapted from http://www.cs.colorado.edu/~kena/classes/5448/f12/lectures/

Today’s Lecture Design patterns – part 1 of a 3-part series Two patterns: Strategy Adapter Assignment 2

Fundamental Principles Apply rigor Separate concerns modularize abstract Anticipate change Generalize Work incrementally

A Checklist on Overall Design Strive for grouping related functionality (high cohesion) Strive for ungrouping semi-related functionality (high cohesion) Strive for reducing interdependency (low coupling)

A Checklist on Class Design Cohesion Completeness Convenience Clarity Consistency

A Checklist on Principles and Strategies keep it simple, stupid! (KISS) information hiding acyclic dependencies … Strategies program to the interface refactor apply software patterns

A Checklist on Principles and Strategies keep it simple, stupid! (KISS) information hiding acyclic dependencies … Strategies program to the interface refactor apply software patterns

Design Patterns “Each pattern describes a problem which occurs over and over again in our environment, and then 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 way twice” [Alexander, Ishikawa, Silverstein 1977] Pattern name problem solution consequences Alexander quote from architecture design Alexander identified these four elements to describe a pattern

Software Design Patterns “Descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context” [Gamma, Helm, Johnson, Vlissides 1995] Pattern name and classification implementation intent sample code also known as known uses motivation related patterns applicability structure participants collaborations consequences intent: description of goal behind pattern and the reason for using it motivation: a scenario consisting of a problem and a context in which the pattern can be used consequences: results, side effects, tradeoffs in using the pattern

Patterns Are Designed to Avoid Redesign (caused by…) Creating an object by specifying a class explicitly Dependence on specific operations Dependence on hardware and software platforms Dependence on object representations or implementations Algorithmic dependencies Tight coupling Extending functionality by subclassing Inability to alter classes conveniently

Patterns Apply Three Design Principles Program to an interface, not an implementation interface should be separately defined, using the construct(s) in the programming language Favor object composition / delegation over inheritance Find what varies and encapsulate it with inheritance, can’t change the interface of a superclass bc changes to a superclass will ripple to the subclasses and all classes that use the subclasses when your goal is code reuse, using composition will yield easier to change code http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition--which-one-should-you-choose-.html

Why Study Design Patterns? (I) Patterns let us reuse solutions that have worked in the past; why waste time reinventing the wheel? have a shared vocabulary around software design they allow you to tell a fellow software engineer, “I used a Strategy pattern here to allow the algorithm used to compute this calculation to be customizable” You don’t have to waste time explaining what you mean since you both know the Strategy pattern

Why Study Design Patterns? (II) Design patterns provide you not with code reuse but with experience reuse Knowing concepts such as abstraction, inheritance, and polymorphism will NOT make you a good designer, unless you use those concepts to create flexible designs that are maintainable and that can cope with change Design patterns can show you how to apply those concepts to achieve those goals

Original Catalogue of Patterns Purpose Creational Structural Behavioral Abstract Factory Builder Factory Method Prototype Singleton Adapter Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor Creational: used to create objects Structural: used to integrate existing code into new OO designs Behavioral: used to manage variations in behavior

Original Catalogue of Patterns Purpose Creational Structural Behavioral Abstract Factory Builder Factory Method Prototype Singleton Adapter Bridge Composite Decorator Façade Flyweight Proxy Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor Creational: used to create objects Structural: used to integrate existing code into new OO designs Behavioral: used to manage variations in behavior Patterns I will be talking about in detail; you should read about the others in the book or online.

Design Pattern by Example SimUDuck: a “duck pond simulator” that can show a wide variety of duck species swimming and quacking Initial State But a request has arrived to allow ducks to also fly. (We need to stay ahead of the competition!) showing display() in subclasses indicates that these classes override the superclass’s display() method

Easy Code Reuse via Inheritance Add fly() to Duck; all ducks can now fly

Whoops! Rubber ducks do not fly! They don’t quack either, so we override quack() to make them squeak We could override fly() in RubberDuck to make it do nothing, but that’s less than ideal, especially…

Double Whoops! …when we might find other Duck subclasses that would have to do the same thing! What was supposed to be a good instance of reuse via inheritance has turned into a maintenance headache!

What about an Interface? Here we define two interfaces and allow subclasses to implement the interfaces they need. What are the trade-offs?

Design Trade-offs With inheritance, we get With interfaces, we get code reuse, only one fly() and quack() method vs. multiple (pro) common behavior in root class, not so common after all (con) With interfaces, we get specificity: only those subclasses that need a fly() method get it (pro) no code re-use: since interfaces only define signatures (con)

Design Principles to the Rescue! Encapsulate What Varies For this particular problem, the “what varies” is the behaviors between Duck subclasses We need to pull out behaviors that vary across the subclasses and put them in their own classes (i.e., encapsulate them) The result: fewer unintended consequences from code changes (such as when we added fly() to Duck) and more flexible code What needs to be taken out of Duck?

Basic Idea Take any behavior that varies across Duck subclasses and pull them out of Duck Duck will no longer have fly() and quack() methods directly Create two sets of classes, one that implements fly behaviors and one that implements quack behaviors Code to an Interface We’ll make use of the “code to an interface” principle and make sure that each member of the two sets implements a particular interface For QuackBehavior, we’ll have Quack, Squeak, Silence For FlyBehavior, we’ll have FlyWithWings, CantFly, FlyWhenThrown, … Additional Benefits Other classes can gain access to these behaviors and we can add additional behaviors without impacting other classes

“Code to Interface” Does NOT Imply Java Interface We are overloading the word “interface” when we say “code to an interface” We can implement “code to an interface” by defining a Java interface and then have various classes implement that interface Or, we can “code to a supertype” and instead define an abstract base class which classes can access via inheritance When we say “code to an interface” it implies that the object that is using the interface will have a variable whose type is the supertype (whether it is an interface or an abstract base class) and thus can point at any implementation of that supertype and is shielded from their specific class names A Duck will point to a fly behavior with a variable of type FlyBehavior NOT FlyWithWings; the code will be more loosely coupled as a result Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

Bringing it all Together: Delegation To take advantage of these new behaviors, we must modify Duck to delegate its flying and quacking behaviors to these other classes rather than implementing this behavior internally We’ll add two attributes that store the desired behavior and we’ll rename fly() and quack() to performFly() and performQuack() this last step is meant to address the issue of it not making sense for a DecoyDuck to have methods like fly() and quack() directly as part of its interface Instead, it inherits these methods and plugs-in CantFly and Silence behaviors to make sure that it does the right things if those methods are invoked This is an instance of the principle “Favor delegation over inheritance”

<<interface>> New Class Diagram <<interface>> FlyBehavior fly() Duck swim() display() setFlyBehavior(FlyBehavior) setQuackBehavior(QuackBehavior) performFly() performQuack() QuackBehavior quack() CantFly FlyWithWings Squeak Quack Silence DecoyDuck RubberDuck RedheadDuck MallardDuck flyBehavior quackBehavior FlyBehavior and QuackBehavior define a set of behaviors that provide behavior to Duck. Duck delegates to each set of behaviors and can switch among them dynamically, if needed. While each subclass now has a performFly() and performQuack() method, at least the user interface is uniform and those methods can point to null behaviors when required.

FlyBehavior.java and QuackBehavior.java

FlyWithWings.java and Squeak.java

Duck.java Note: “code to interface”, delegation, encapsulation, and ability to change behaviors dynamically code to interface = using, e.g., quackBehavior.quack() instead of e.g., Squeak.quack()… you’re using the interface’s methods rather than the concrete class’s methods If you use Squeak.quack() and then you get rid of the Squeak class, you have to change all the references to squeak.

RubberDuck.java

DuckSimulator.java (Part 1) Note: all variables are of type Duck, not the specific subtypes; “code to interface” in action Note: here we see the power of delegation. We can change behaviors at run-time

DuckSimulator.java (Part 2) Because of abstraction and polymorphism, processDucks() consists of nice, clean, robust, and extensible code!

Demo

Not Completely Decoupled Is DuckSimulator completely decoupled from the Duck subclasses? All of its variables are of type Duck No! The subclasses are still coded into DuckSimulator Duck myDuck = new RubberDuck(); This is a type of coupling… Fortunately, we can eliminate this type of coupling if needed, using a pattern called Factory. We’ll see Factory in action in a later lecture

Meet the Strategy Design Pattern The solution that we applied to this design problem is known as the Strategy Design Pattern It features the following design concepts/principles: Encapsulate what varies Code to an Interface Delegation Favor Delegation over Inheritance Definition: The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it

Structure of Strategy client = DuckSimulator host = Duck Algorithm/strategy = FlyBehavior, QuackBehavior ConcreteAlgorithms = Quack, Silence, FlyWithWings, etc. Algorithm is pulled out of Host. Client only makes use of the public interface of Algorithm and is not tied to concrete subclasses. Client can change its behavior by switching among the various concrete algorithms

Robotic Duck? Says “hello” instead of quack Flies with a retractable helicopter propeller

Swim Behavior?

Adapters in the Real World Our next pattern provides steps for converting an incompatible interface with an existing system into a different interface that is compatible Real world example: AC power adapters Electronic products made for the USA cannot be used directly with outlets found in most other parts of the world To use these products outside the US, you need an AC power adapter

Software Adapters (I) Pre-condition: You are maintaining an existing system that makes use of a third-party class library from vendor A Stimulus: Vendor A goes belly up and corporate policy does not allow you to make use of an unsupported class library Response: Vendor B provides a similar class library but its interface is completely different from the interface provided by vendor A Assumptions: You don’t want to change your code, and you can’t change vendor B’s code Solution?: Write new code that adapts vendor B’s interface to the interface expected by your original code

Software Adapters (II)

Software Adapters (III) …plug it in Benefit: Existing system and new vendor library do not change—new code is isolated within the adapter

Example: A Turkey Amongst Ducks! (I) If it walks like a duck and quacks like a duck, then it must be a duck!

Example: A Turkey Amongst Ducks! (I) If it walks like a duck and quacks like a duck, then it must be a duck! Or… It might be a turkey wrapped with a duck adapter!

Example: A Turkey Amongst Ducks! (II) A slightly different duck model

Example: A Turkey Amongst Ducks! (III) An interloper wants to invade the simulator But the duck simulator doesn’t know how to handle turkeys, only ducks!

Example: A Turkey Amongst Ducks! (IV) Solution: Write an adapter that makes a turkey look like a duck 1. Adapter implements target interface (Duck) 2. Adaptee (turkey) is passed via constructor and stored internally 3. Calls by client code are delegated to the appropriate methods in the adaptee 4. Adapter is full-fledged class, could contains additional vars and methods to get its job done; can be used polymorphically as a Duck

DuckSimulator.java

Demo

Adapter Pattern: Definition The Adapter pattern converts the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. The client makes a request on the adapter by invoking a method from the target interface on it quack() The adapter translates that request into one or more calls on the adaptee using the adaptee interface turkey.gobble() The client receives the results of the call and never knows there is an adapter doing the translation

Adapter Pattern: Structure client = DuckSimulator Target interface = Duck interface Adapter = TurkeyAdapter request = quack() Adaptee = Turkey specificRequest = gobble() Draw UML on board

Penguin Adapter?

Assignment 2

Next Time More patterns!