1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.

Slides:



Advertisements
Similar presentations
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.
Advertisements

+ Informatics 122 Software Design II Lecture 7 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
Design Patterns Section 7.1 (JIA’s) Section (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section (JIA’s)
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 Open-closed principle.
COP 3331 Object Oriented Analysis and Design Chapter 7 – Design by Abastraction Jean Muhammad.
CS 210 Proxy Pattern Nov 14 th, Revisit the Gumball machine example The same example covered in the State pattern Now we want to add some monitor.
Informatics 122 Software Design II
Strategy Pattern1 Design Patterns 1.Strategy Pattern How to design for flexibility?
Design Patterns Copyright © Vyacheslav Mukhortov, Nikita Nyanchuk-Tatarskiy, Copyright © INTEKS LLC,
DESIGN PATTERNS OZGUR RAHMI DONMEZ.
Informatics 122 Software Design II Lecture 5 Emily Navarro Duplication of course material for any commercial purpose without the explicit written permission.
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 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.
ECE 355 Design Patterns Tutorial Part 2 (based on slides by Ali Razavi) Presented by Igor Ivković
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.
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.
Programming With Java ICS201 University Of Hail1 Chapter 12 UML and Patterns.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Chapter 1: Introduction to Design Patterns. SimUDuck Example.
CSE 332: Design Patterns (Part I) Introduction to Design Patterns Design patterns were mentioned several times so far –And the Singleton Pattern was discussed.
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.
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
SOEN 6011 Software Engineering Processes Section SS Fall 2007 Dr Greg Butler
Behavioral Design Patterns Morteza Yousefi University Of Science & Technology Of Mazandaran 1of 27Behavioral Design Patterns.
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.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
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.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
Behavioral Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
Design Patterns: Design by Abstraction
CS 210 Final Review November 28, CS 210 Adapter Pattern.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Design Patterns Introduction
Java Design Patterns Java Design Patterns. What are design patterns? the best solution for a recurring problem a technique for making code more flexible.
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 و ابتغ فيما آتاك الله الدار.
CS 210 Introduction to Design Patterns August 29, 2006.
STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise
CS 210 Review October 3, 2006.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
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.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
TEMPLATE METHOD DESIGN PATTERN -SWAPNIL SHAH. WHAT IS A DESIGN PATTERN… A design pattern is a general reusable solution to a commonly occurring problem.
SE 461 Software Patterns Welcome to Design Patterns.
Intro to Design Pattern
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Strategy Pattern.
Chapter 5:Design Patterns
MPCS – Advanced java Programming
Design Patterns Lecture part 2.
Introduction to Design Patterns
Behavioral Design Patterns
Strategy Design Pattern
SE-2811 Software Component Design
Introduction to Behavioral Patterns (2)
Informatics 122 Software Design II
SE-2811 Software Component Design
DESIGN PATTERNS : State Pattern
Informatics 122 Software Design II
Software Design Lecture : 27.
Presentation transcript:

1 Unit 5 Design Patterns: Design by Abstraction

2 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.

3 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.

4 GoF Patterns Creational StructuralBehavioral Abstract FactoryAdapter Chain of Responsibility Builder BridgeCommand Factory MethodCompositeInterpreter Prototype DecoratorIterator Singleton FaçadeMediator FlyweightMemento ProxyObserver 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.

5 Generic 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 of designing generic components Refactoring Generalizing

6 Refactoring  Definition 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) Capture the logic in a generic component Restructure by replacing every occurrence of the code segment with a reference to the generic component

7 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

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

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

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

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

e.g.Duck pond simulation game 12 Duck quack() swim() display() MallardDuck display() RedheadDuck display() other Duck

 Add fly() method  Solution : add fly() in base class  But RubberDuck can’t fly nor quack it can squeak so override quack method & fly method to ‘no fly’  We need to override every method that needs change 13

 Solution: use of interface flyable & quackable 14 Duck quack() swim() display() MallardDuck fly() quack() display() RedheadDuck fly() quack() display() RubberDuck quack() display() Flyable fly() Quackable quack()

 No reuse of code as every class has to implement code for the interface  Solution: take what varies & “encapsulate” it so it won’t affect the rest of the code  Later encapsulated part can be extended without affecting rest of the code  All patterns provide a way to let some part of a system vary independently of all other parts 15

 So pull out the duck behaviors fly & quack  Change the behavior at run time 16 > FlyBehavior fly() FlyWithWings fly() { // implements duck flying } FlyNoWay fly() { // do nothing can’t fly }

 Simi. interface QuackBehavior is implemented by Quack, Squeak & MuteQuack classes  Other objects can reuse fly & quack behaviors as these are no longer hidden in Duck class  Also we can add new behavior without disturbing existing behaviors 17

18 e.g.Duck pond simulation game 18 Duck FlyBehavior flyBehavior QuackBehavior quackBehavior swim() display() performQuack() performFly() setFlyBehavior(FlyBehavior fb) setQuackBehavior(QuackBehavior qb) MallardDuck display() RedheadDuck display() RubberDuck display() Encapsulated Fly behavior Encapsulated Quack behavior

 Client makes use of an encapsulated family of algorithms for both flying & quacking  Favor composition over inheritance  Duck class is composed of right behavior object 19

20 Question  Have we used the Strategy Pattern before?

Example : 21

State Design Pattern  State pattern is one of the behavioral design pattern.  State design pattern is used when an Object change its behavior based on its internal state.  22

e.g. Gumball machine state diagram  Insert quarter  eject quarter turns crank  gumballs=0  gumballs>0   dispense gumball 23 Out of Gumballs No Quarter Gumball sold Has Quarter

Java program Public class GumballMachine { final static int SOLD_OUT=0; final static int NO_QUARTER=1; final static int HAS_QUARTER=2; final static int SOLD=3; int state=SOLD_OUT; int count =0; public void insertQuarter() { if(state==HAS_QUARTER) { SOP(“You can’t insert another quarter”); } else if(state==NO_QUARTER) { SOP(“You inserted a quarter”); state= HAS_QUARTER; } 24

else if(state==SOLD_OUT) { SOP(“You can’t insert a quarter, the m/c is sold out”); } else if(state==SOLD) { SOP(“please wait we are already giving a gumball”); } public void ejectQuarter() { if(state==HAS_QUARTER) { SOP(“quarter RETURNED”); } ………………………… 25

 If want to add new state “WINNER”, every method need to be changed as per new state  Instead use interfaces & separate states from code  Map each state to a class  Similar to strategy design pattern 26

27 > State insertQuarter() ejectQuarter() turnCrank() dispense() SoldState insertQuarter() ejectQuarter() turnCrank() dispense() SoldOutState insertQuarter() ejectQuarter() turnCrank() dispense() NoQuarterState insertQuarter() ejectQuarter() turnCrank() dispense() HasQuarterState insertQuarter() ejectQuarter() turnCrank() dispense()

 If you are in NO_QUARTER state & you invoked 1.inserQuarter() method, set gumballMachinneState=HAS_QuarterState  2. ejectQuarter() SOP(“u havent inserted quarter”)  3. turnCrank() SOP(“There is no quarter”)  4. dispense() SOP(“u to pay first”) 28

e.g. TV Remote Suppose we want to implement a TV Remote with a simple button to perform action, if the State is ON, it will turn on the TV and if state is OFF, it will turn off the TV. State Interface First of all we will create State interface that will define the method that should be implemented by different concrete states and context class. State.java package com.journaldev.design.state; public interface State { public void doAction(); } Concrete State Implementations In our example, we can have two states – one for turning TV on and another to turn it off. So we will create two concrete state implementations for these behaviors. 29

Context Implementation TVContext.java public class TVContext implements State { private State tvState; public void setState(State state) { this.tvState=state; } public State getState() { return this.tvState; public void doAction() { this.tvState.doAction(); } } Notice that Context also implements State and keep a reference of its current state and forwards the request to the state implementation. 30

TVStartState.java public class TVStartState implements State public void doAction() { System.out.println("TV is turned ON"); } } TVStopState.java package com.journaldev.design.state; public class TVStopState implements State public void doAction() { System.out.println("TV is turned OFF"); } Now we are ready to implement our Context object that will change its behavior based on its internal state. 31

Test Program Now let’s write a simple program to test our implementation of TV Remote using State pattern. TVRemote.java public class TVRemote { public static void main(String[] args) { TVContext context = new TVContext(); State tvStartState = new TVStartState(); State tvStopState = new TVStopState(); context.setState(tvStartState); context.doAction(); context.setState(tvStopState); context.doAction(); } } Output of above program is same as the basic implementation of TV Remote without using any pattern. The benefits of using State pattern to implement polymorphic behavior is clearly visible, the chances of error are less and its very easy to add more states for additional behavior making it more robust, easily maintainable and flexible. Also State pattern helped in avoiding if-else or switch-case conditional logic in this scenario. 32

e.g. of Strategy design pattern For our example, we will try to implement a simple Shopping Cart where we have two payment strategies – using Credit Card or using PayPal. First of all we will create the interface for our strategy, in our case to pay the amount passed as argument. PaymentStrategy.java public interface PaymentStrategy { public void pay(int amount); } Now we will have to create concrete implementations of algorithms for payment using credit/debit card or through paypal. 33

PaypalStrategy.java public class PaypalStrategy implements PaymentStrategy { private String Id; private String password; public PaypalStrategy(String , String pwd){ this. Id= ; this.password=pwd; public void pay(int amount) { System.out.println(amount + " paid using Paypal."); } } Now our algorithms are ready and we can implement Shopping Cart and payment method will require input as Payment strategy. 34

Item.java package com.journaldev.design.strategy; public class Item { private String upcCode; private int price; public Item(String upc, int cost){ this.upcCode=upc; this.price=cost; } public String getUpcCode() { return upcCode; } public int getPrice() { return price; } } 35

ShoppingCart.java package com.journaldev.design.strategy; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class ShoppingCart { //List of items List items; public ShoppingCart(){ this.items=new ArrayList (); } public void addItem(Item item){ this.items.add(item); } public void removeItem(Item item){ this.items.remove(item); } public int calculateTotal(){ int sum = 0; for(Item item : items){ sum += item.getPrice(); } return sum; } public void pay(PaymentStrategy paymentMethod){ int amount = calculateTotal(); paymentMethod.pay(amount); } Notice that payment method of shopping cart requires payment algorithm as argument and doesn’t store it anywhere as instance variable. Let’s test our setup with a simple program. ShoppingCartTest.java shoppingCartTest.java package com.journaldev.design.strategy; public class ShoppingCartTest { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); Item item1 = new Item("1234",10); Item item2 = new Item("5678",40); cart.addItem(item1); cart.addItem(item2); //pay by paypal cart.pay(new "mypwd")); //pay by credit card cart.pay(new CreditCardStrategy("Pankaj Kumar", " ", "786", "12/15")); } } O package com.journaldev.design.strategy; public class CreditCardStrategy implements PaymentStrategy { private String name; private String cardNumber; private String cvv; private String dateOfExpiry; public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ this.name=nm; this.cardNumber=ccNum; this.cvv=cvv; this.dateOfExpiry=expiryDate; public void pay(int amount) { System.out.println(amount +" paid with credit/debit card"); } } Output of above program is: paid using Paypal. 50 paid with credit/debit card 36