Design Patterns: Design by Abstraction

Slides:



Advertisements
Similar presentations
Design Patterns.
Advertisements

Creational Design Patterns. Creational DP: Abstracts the instantiation process Helps make a system independent of how objects are created, composed, represented.
Design Patterns based on book of Gang of Four (GoF) Erich Gamma, Richard Helm, Ralph Johnson, and John VlissidesGang of Four (GoF) Elements of Reusable.
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.
1 Object Oriented Programming Lecture XII The Adapter,Template, Strategy and Factory design patterns.
1 More Design Patterns CS 3331 Fall GoF Patterns Creational StructuralBehavioral Abstract FactoryAdapter Chain of Responsibility Builder BridgeCommand.
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
COP 3331 Object Oriented Analysis and Design Chapter 7 – Design by Abastraction Jean Muhammad.
Object Oriented Programming Lecture 7: Algorithm animation using strategy and factory patterns, The Adapter design pattern
Design Patterns for Object Oriented systems CSC 515 Ashwin Dandwate.
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
IEG3080 Tutorial 7 Prepared by Ryan.
Design Patterns CS is not simply about programming
Abstract Classes An abstract class is a class with partial implementation. It implements behaviors that are common to all subclasses, but defers to the.
Enahnced Digital Clock Applet Setting applet parameters in the web page. The applet tag in HTML:
Design Patterns William A. Hoffman NYU OOP Class.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
PRESENTED BY SANGEETA MEHTA EECS810 UNIVERSITY OF KANSAS OCTOBER 2008 Design Patterns.
1 Features of Java CS 3331 Fall Outline  Abstract class  Interface  Application --- animation applets.
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 CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
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.
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.
1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Object Oriented Programming Lecture 5: Refactoring by Inheritance and Delegation - A simple Design Pattern for animation applets, A Generic Function Plotter.
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.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
1 Object Oriented Programming Lecture XI An abstract function plotter, using the Template and the Strategy design patterns.
Design Patterns Yonglei Tao. Design Patterns  A design pattern describes a recurring design problem, a solution, and the context in which that solution.
SWE 316: Software Design and Architecture – Dr. Khalid Aljasser Objectives Lecture 13 Creational Design Pattern SWE 316: Software Design and Architecture.
Programmeerimine Delphi keskkonnas MTAT Programmeerimine Delphi keskkonnas MTAT Jelena Zaitseva
Features of Java CS 3331 Sections and 5.5.
Design Patterns Introduction
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
CS251 – Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 و ابتغ فيما آتاك الله الدار.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
CSC 480 Software Engineering Design With Patterns.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
StarBuzz Coffee Recipe Boil some water Brew coffee in boiling water Pour coffee in cup Add sugar and milk Tea Recipe Boil some water Steep tea in boiling.
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
Design Patterns Creational Patterns. Abstract the instantiation process Help make the system independent of how its objects are created, composed and.
TEMPLATE METHOD DESIGN PATTERN -SWAPNIL SHAH. WHAT IS A DESIGN PATTERN… A design pattern is a general reusable solution to a commonly occurring problem.
Design Patterns CSCE 315 – Programming Studio Spring 2013.
1 Lecture Material Design Patterns Visitor Client-Server Factory Singleton.
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Chapter 10 Design Patterns.
Chapter 5:Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Software Design and Architecture
object oriented Principles of software design
Informatics 122 Software Design II
Design by Abstraction (Continuation) CS 3331 Spring 2005
CSC 480 Software Engineering
Presentation transcript:

Design Patterns: Design by Abstraction CS 3331 Chapter 7 of [Jia03]

Outline Design pattern Reusable component Template method Strategy pattern Factory pattern

Motivation Modeling the solar system 1..* 0..* Sun Planet Moon Q: How to make sure that there exists only one Sun object in the system?

In Java … public class Sun { private static Sun theInstance = new Sun(); private Sun() { /* … */ } public static Sun getInstance() { return theInstance; } // the rest of code … Q1: Can the client create more than one Sun? Q2: Can the client access the unique Sun?

In General … T - theInstance: T { static } T() + getInstance(): T { static } return theInstance;

Singleton Design Pattern Intent To ensure that a class has only one instance and provides a global access point to it Applicability Use the Singleton pattern when there must be exactly one instance of a class and it must be accessible to clients from a well-known access point Benefits Controlled access to the sole instance Permits a variable number of instances

Example Define a Calendar class using the Singleton pattern. public class Calendar { // the rest of code … }

What Are Design Patterns? Design patterns are: Schematic descriptions of design solutions to recurring problems in software design, and Reusable (i.e., generic), but don’t have to be implemented in the same way. That is, describe: Design problems that occur repeatedly, and Core solutions to those problems.

Why Design Patterns? To capture and document software design knowledge. => helps designers acquire design expertise. To support reuse in design and boost confidence in software systems. To provide a common vocabulary for software designers to communicate their designs.

GoF Patterns Creational Structural Behavioral Abstract Factory Adapter Chain of Responsibility Builder Bridge Command Factory Method Composite Interpreter Prototype Decorator Iterator Singleton Façade Mediator Flyweight Memento Proxy Observer State Strategy Template Method Visitor E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995.

Outline Design pattern Reusable component Template method Strategy pattern Factory pattern

Generic (Reusable) Components Generic components Program components (e.g., classes and packages) that can be extended, adapted, and reused in many different contexts without having to modify the source code Also known as reusable components Techniques for designing generic components Refactoring Generalizing

Refactoring Definition Approach Refactoring means restructuring a program to improve its structure (e.g., to eliminate duplicate code segments) without changing its functionality Approach Identify code segment that implements the same logic (e.g., duplicate code) => Commonality and variability analysis Capture the logic in a generic component Restructure by replacing every occurrence of the code segment with a reference to the generic component

Refactoring Duplication Why? Hazardous for maintenance Changes must be repeated everywhere Some may be overlooked or forgotten Thus, code segments can easily drift apart Approach Refactoring by inheritance Refactoring by delegation

Refactoring by Inheritance Sample code: any duplicate? class A { void m1() { // … step1(); step2(); step3(); } class B { void m2() { // … step1(); step2(); step3(); }

Refactored Code class C { void computeAll() { step1(); step2(); } class A extends C { void m1() { // … computeAll(); } class B extends C { void m2() {

Refactoring by Delegation class Helper { void computeAll() { step1(); step2(); step3(); } class A { void m1() { // … h.computeAll(); } Helper h; class B { void m2() { Q. Compare the two?

Exercise Identify and remove duplicate code. public class Point { public Point(int x, int y) { this.x = x; this.y = y; } protected int x, y; // other code; public class ColoredPoint extends Point { public ColoredPoint(int x, int y, Color c) { this.x = x; this.y = y; this.c = c; } protected Color c; // other code

Generic Animation Applet Reusable class that supports the animation idiom Applet timer AnimationApplet {abstract} # delay: int # dim: Dimension + init() + start() + stop() Timer

Animation Applet (Cont.) public abstract class AnimationApplet extends java.applet.Applet { protected Timer timer; protected int delay = 100; protected Dimension dim; public void init() { dim = getSize(); String att = getParameter(“delay”); if (att != null ) { delay = Integer.parseInt(att); } timer = new Timer(delay, e -> repaint()); <<continue to the next page>>

Animation Applet (Cont.) public void start() { timer.start(); } public void stop() { timer.stop();

Using Animation Applet Reimplement the DigitalClock applet to use the animation applet class. DigitalClock init() start() stop() paint() DigitalClock paint() AnimationApplet

Generic Double-Buffered Animation Applet Reusable class that supports double-buffered animation Applet DBAnimationApplet {abstract} init() initAnimation() update() paint() paintFrame() {abstract} AnimationApplet {abstract} image Image offScreen Graphics

DB Animation Applet (Cont.) public abstract class DBAnimationApplet extends AnimationApplet { protected Image image; protected Graphics offscreen; protected boolean doubleBuffered; <<constructors>> <<initialization>> <<updating and painting>> }

Constructors Question Why protected constructors? protected DBAnimationApplet(boolean doubleBuffered) { this.doubleBuffered = doubleBuffered; } protected DBAnimationApplet() { this(true); Question Why protected constructors?

Initialization Questions Why “final” init? final public void init() { super.init(); image = createImage(dim.width, dim.height); offscreen = image.getGraphics(); initAnimator(); } protected void initAnimator() {} Questions Why “final” init? Why “protected” and separate initAnimator? What’s the difference between constructors and init methods?

Updating and Painting Questions final public void update(Graphics g) { if (doubleBuffered) { paintFrame(offscreen); g.drawImage(image, 0, 0, this); } else { paintFrame(g); } final public void paint(Graphics g) { update(g); protected abstract void paintFrame(Graphics g); Questions Why “final” update and paint, and why “abstract” paintFrame? How does this cater for both double-buffered and non-DB animation?

Example Rewrite the bouncing ball applet to use the DBAnimationApplet class. Note that: init() calls initAnimation() which is overridden in the subclass, and Both update() and paint() call paintFrame() which is overridden in the subclass. DBAnimationApplet init() initAnimator() update() paint() paintFrame() BouncingBall

Bouncing Ball Animation public class BouncingBall extends DBAnimationApplet { private int x, y; private int dx = -2, dy = -4; private int radius = 20; private Color color = Color.GREEN; protected void initAnimator() { x = dim.width * 2 / 3; y = dim.height - radius; } << paintFrame method >>

Bouncing Ball Animation (Cont.) protected void paintFrame(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, dim.width, dim.height); if (x < radius || x > dim.width - radius) { dx = -dx; } if (y < radius || y > dim.height - radius) { dy = -dy; x += dx; y += dy; g.setColor(color); g.fillOval(x - radius, y - radius, radius * 2, radius * 2);

Template Methods Intent To define a skeleton algorithm by deferring some steps to subclasses To allow the subclasses to redefine certain steps AbstractClass templateMethod() hookMethod1() hookMethod2() ConcreteClass …

Template Methods (Cont.) Terminology Hook methods: placeholders for the behaviour to be implemented by subclasses Template methods: methods containing hook methods Hot spots: changeable behaviours of generic classes represented by hook methods Frozen spots: fixed behaviours of generic classes represented by template methods

Exercise Identify hook methods and template methods in the DBAnimationApplet class.

Exercise: Solar System Write an animation applet that shows the sun and a planet orbiting around the sun. Use the DBAnimationApplet class.

More Example Generic function plotter To plot arbitrary single-variable functions on a two-dimensional space Applet Plotter func() paint() plotFunction() drawCoordinates() … func() PlotSine func() PlotCosine func()

Exercise Complex numbers, x + y*i Rectangular Polar imaginary (x, y) real imaginary Polar (r, a) r a

Exercise (Cont.) Complex add() mul() realPart() imaginaryPart() magnitude() angle() RectangularComplex PolarComplex

Exercise (Cont.) Write the template methods add and mul. // Assume constructors RectangularComplex(int real, int imag) and // PolarComplex(int magnitude, int angle). public Complex add(Complex c) { } public Complex mul(Complex c) {

Outline Design pattern Reusable component Template method Strategy pattern Factory pattern

Generalization Definition Example Process that takes a solution to a specific problem and restructures it to solve a category of problems similar to the original problem Example Generalize the plotter class to support multiple functions

Review Generic function plotter To plot arbitrary single-variable functions on a two-dimensional space Applet Plotter func() paint() plotFunction() drawCoordinates() … func() PlotSine func() PlotCosine func()

Generic Multiple Function Plotter Applet 1..* Plotter func() paint() plotFunction() drawCoordinates() MultiPlotter initMultiPlotter() init() addFunction() plotFunction() func() Function apply() Sine apply() <<create>> PlotSineCosine initMultiPlotter() Cosine apply() <<create>>

Multiple Function Plotter (Cont.) Method Description initMultiPlotter() Hook method for subclasses to set up functions to be plotted init() Template method for initialization which calls initMultiPlotter() addFunction() Method to add a function to be plotted plotFunction() Auxiliary function called by paint() to plot the functions func() Method inherited from class Plotter that is no longer useful in this class

Strategy Design Pattern Intent To define a family of algorithms, encapsulate each one, and make them interchangeable Context contextMethod() strategy ConcreteStrategyA algorithm() Strategy alogorithm() ConcreteStrategyB strategy.algorithm()

Question Have we used the Strategy Pattern before?

Abstract Coupling Definition Example Question Abstract coupling means a client access a service through an interface or an abstract class without knowing the actual concrete class that provide the service Example Strategy pattern Iterator pattern Question Why abstract coupling?

Design Guideline Program to an interface, not to an implementation!

Iterating over Collection Accessing all elements of collection objects such as sets, bags, lists, etc. Collection<T> c; … c= new ArrayList<>(); for (Iterator<T> i = c.iterator(); i.hasNext(); ) { T elem = i.next(); } // since Java 5 if c is of type Iterable<T> for (T elem: c) { … elem …

<<create>> Iterator Pattern Intent To provide a way to access the elements of a collection sequentially <<use>> Iterator hasNext() next() Collection iterator() ConcreteCollection iterator() ConcreteIterator hasNext() next() <<create>> return new ConcreteIterator()

Exercise Fill out the missing part to implement the Iterator interface public class Library { private Book[] books; /** Returns an iterator enumerating all books of this library. */ public Iterator<Book> books() { return new LibraryIterator(books); } private static class LibraryIterator implements java.util.Iterator<Book> { public void remove() { throw new UnsupportedOperationException(); } // YOUR CODE HERE … }

Factory Design Pattern Intent To decouple object creation from its use and to support different way of creating objects To define an interface for creating objects but let subclasses decide which class to instantiate and how Product Client AbstractFactory makeProduct() create ConcreteFactory makeProduct() ConcreteProuct

Example Complex numbers ComplexFactory makeComplext() Complex <<create>> PolarFactory makeComplex() PolarComplex <<create>> RectangularFactory makeComplex() RectangularComplex