Introduction to Behavioral Patterns (2)

Slides:



Advertisements
Similar presentations
UML State Machine Diagrams and Modeling
Advertisements

Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
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.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
SWE 4743 Strategy Patterns Richard Gesick. CSE Strategy Pattern the strategy pattern (also known as the policy pattern) is a software design.
CS 106 Introduction to Computer Science I 12 / 04 / 2006 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Delegates & Events Observer and Strategy Patterns Game Design Experience Professor Jim Whitehead January 30, 2009 Creative Commons Attribution 3.0 creativecommons.org/licenses/by/3.0.
What is an object? Your dog, your desk, your television set, your bicycle. Real-world objects share two characteristics: They all have state and behavior;
Classes in C++ Bryce Boe 2012/08/15 CS32, Summer 2012 B.
1 CSC241: Object Oriented Programming Lecture No 07.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Introduction to Object Oriented Design. Topics Designing Your Own Classes Attributes and Behaviors Class Diagrams.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
An Introduction to Design Patterns. Introduction Promote reuse. Use the experiences of software developers. A shared library/lingo used by developers.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 13 Inheritance and Polymorphism.
3-1 State Design Pattern C Sc 335 Rick Mercer. State Design Pattern State is one of the Behavioral patterns It is similar to Strategy Allows an object.
Chapter 5 Implementing UML Specification (Part II) Object-Oriented Technology From Diagram to Code with Visual Paradigm for UML Curtis H.K. Tsang, Clarence.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
More Design Patterns From: Shalloway & Trott, Design Patterns Explained, 2 nd ed.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
The State Design Pattern A behavioral design pattern. Shivraj Persaud
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
GRASP – Designing Objects with Responsibilities
University of Central Florida COP 3330 Object Oriented Programming
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Polymorphism.
Review: Two Programming Paradigms
University of Central Florida COP 3330 Object Oriented Programming
Programming Design Patterns
Creating and Using Classes
Programming Design Patterns
CS212: Object Oriented Analysis and Design
Interface.
State Design Pattern 1.
Object-Oriented Programming
Introduction to Behavioral Patterns (1)
Week 6 Object-Oriented Programming (2): Polymorphism
Object-Oriented Programming Using C++ Second Edition
Interfaces.
Classes and Objects.
DESIGN PATTERNS : State Pattern
CS 350 – Software Design Principles and Strategies – Chapter 14
Strategy Design Pattern
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Object-Oriented Programming
Overview of C++ Polymorphism
Java objects: a first view
Review of Previous Lesson
Object Oriented Design & Analysis
Software Design Lecture : 28.
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Lecture 6: Polymorphism
Presentation transcript:

Introduction to Behavioral Patterns (2) 11/28/2018 Programming Design Patterns

Programming Design Patterns Design Problem Given a gumball machine that works in the following way: If a user enters a quarter, change the state to “HAS_QUARTER”, then allow the user to turn the crank. change the state of the machine to GUMBALL_SOLD reduce the number of available gumballs, and if the number is 0, then change the state to OUT_OF_GUMBALLS. If the user ejects the quarter, change the state of the machine to “NO_QUARTER” Use the given State diagram Write code for a Gumball machine that implements the given state diagram Programming Design Patterns 11/28/2018

State diagram: Gumball machine Programming Design Patterns 11/28/2018

Coding a State Machine: attempt 1 How many states are available? NO_QUARTER, HAS_QUARTER, OUT_OF_GUMBALLS, GUMBALL_SOLD In code, these should all be “final static int” variables Need an instance variable to hold the current state What are the user actions possible on the machine? insert quarter turn crank eject quarter dispense (internal action) Programming Design Patterns 11/28/2018

Coding a State Machine (2) public class GumballMachine { final static int SOLD_OUT = 0; // initialize other states // initialize number of gumballs int count = 0; // initialize the current state int currentState = SOLD_OUT; public GumballMachine (int countIn) { count = countIn; } // … Programming Design Patterns 11/28/2018

Coding a State Machine (3) public void insertQuarter() { if (state == HAS_QUARTER) { // Classwork: // add comments, instead of real code, for now } // REST OF THE CODE Programming Design Patterns 11/28/2018

Coding a State Machine (3) public void insertQuarter() { if (state == HAS_QUARTER) { // can’t insert another quarter } else if (state == NO_QUARTER) { // change state to HAS_QUARTER } else if (state == SOLD_OUT) { // error, can’t insert as the machine is out of gumballs } else if (state == SOLD) { // wait, a gumball is being dispensed } AWT: abstract windowing toolkit Programming Design Patterns 11/28/2018

Coding a State Machine (4) public void insertQuarter() { } public void ejectQuarter() { public void turnCrank() { public void dispense() { // all methods have a similar “structure” Programming Design Patterns 11/28/2018

Coding a State Machine (5) Now, if a scheme is launched so that once in every 10 uses of the machine 2 gumballs are dispensed. Make the necessary changes to the code. Evaluate your design Programming Design Patterns 11/28/2018

Coding a State Machine: Design Follows the open-closed principle? What varies has been encapsulated? encapsulate the change in a different class(es) Error prone to changes? Programming Design Patterns 11/28/2018

Coding a State Machine: Design Code isn’t adhering to the open-closed principle State transitions are buried in the middle of conditional statements What varies has not been encapsulated The Gumball class should not be changed, whenever the logic of each action/state changes encapsulate the change in a different class(es) Error prone to changes AWT: abstract windowing toolkit Programming Design Patterns 11/28/2018

Designing a State Machine Define an interface with a method for each action Implement a State class for every state of the machine these classes are responsible for actions in that state. Get rid of conditional code delegate it to the state classes. i.e. delegate the actions to the respective State classes use an instance variable to keep track of the current state AWT: abstract windowing toolkit Programming Design Patterns 11/28/2018

State Pattern: Gumball Machine Apply the State pattern to the state machine shown in the diagram page 386 New code needs to be added to the Gumball class to instantiate the new State. Then, just add the new classes for the State. Programming Design Patterns 11/28/2018

Programming Design Patterns State Interface public interface State { public void insertQuarter(); public void ejectQuarter(); public void turnCrank(); public void dispense(); } Programming Design Patterns 11/28/2018

State Pattern: Context Class public class GumballMachine { // declare all States, count of gumballs, currentState // constructor: initialize count, state objects public void insertQuarter() { // delegate to the insertQuarter() method of the relevant state } public void ejectQuarter() { // delegate … // Ok for the Gumball machine itself to implement the State interface Programming Design Patterns 11/28/2018

State Pattern: Context Class public class GumballMachine { State soldOutState, noQuarterState, …; State currentState = …; int count = 0; public GumballMachine(int noOfGumballs) { if (count > 0) {// change state } // initialize all the State objects // pass a reference to “this” to the State objects } public void insertQuarter() { currentState.insertQuarter(); } public void ejectQuarter() { currentState.ejectQuarter();} … Programming Design Patterns 11/28/2018

State Class Implementation public class HasQuarterState implements State { // Classwork: // constructor: take the gumball machine // for each method of the interface, // implement the method (just add comments for now) } Programming Design Patterns 11/28/2018

State Class Implementation public class HasQuarterState implements State { // constructor: take the gumball machine public void insertQuarter() { // error message, can’t insert another quarter } public void ejectQuarter() { // change state of the machine. // use the reference to Gumball context class // passed in the constructor public void turnCrank() {…} public void dispense() {…} Programming Design Patterns 11/28/2018

State Pattern: Open to extension? Now assume more states need to be added what code needs to be added and where Add a new state in the Context class, create a new class for the State. Programming Design Patterns 11/28/2018

State Pattern: basic idea Changes the structure of the code (compare with the initial implementation) functionality, however, remains exactly the same Gets rid of error-prone if-statements difficult to maintain such code Each state is closed for modification but the Gumball machine is open for extension Localized the behavior of each state to its own class New code needs to be added to the Gumball class, and then just to the new classes. Programming Design Patterns 11/28/2018

Programming Design Patterns State Pattern: basic Gumball class is the "context" class that presents a single interface to clients. Define a State abstract base class or an Interface. “States" of the state machine are derived classes of the State base class. Localize state-specific code into respective derived classes. The Context class has a pointer to "state" classes. To change the state, the pointer to current-state is changed in the Context class. New code needs to be added to the Gumball class, and then just to the new classes. Programming Design Patterns 11/28/2018

State Pattern: definition Allows an object to alter its behavior when its internal state changes. The object will appear to change its class. What does this mean? Homework Checkout the class diagram for State Pattern Homework: page 410 Because of composition, the behavior of the object is changed, and so to the client it appears as if the object was instantiated from some other class. Programming Design Patterns 11/28/2018

State Pattern: questions Should the code for transition between states be placed in the State classes or in the Context class? Homework Should the clients interact with State classes? Yes/No: why? Place it in the Context class, or else there are dependencies between the State classes. Page 412. No, the clients should interact just with the Context class. The use of State classes should be hidden. Programming Design Patterns 11/28/2018

Programming Design Patterns Design Problem (2) A database gets connections from 3 kinds of users developers sales accounting Connections from all the 3 categories (listed above) need to perform the following functions: open, update, log, close Design the Database connection control using the State pattern Even though State is an incorrect pattern for this problem Programming Design Patterns 11/28/2018

Database Connection Design (1) What are the States? DEVELOPER, SALES, ACCOUNTING a class for each one of these What are the actions? open, update, log, close these are methods of the interface Programming Design Patterns 11/28/2018

Database Connection Design (2) What are the States? DEVELOPER, SALES, ACCOUNTING a class for each one of these What are the actions? open, update, log, close these are methods of the interface Programming Design Patterns 11/28/2018

Database Connection Design (3) public interface State { public void open(); public void close(); public void update(); public void log(); } Programming Design Patterns 11/28/2018

Database Connection Design (3) class Developer implements State { public void open() { ..} public void close() { …} public void update() { …} public void log() { …} } class Sales implements State { Programming Design Patterns 11/28/2018

Database Connection Design (3) public class Connection { State developer, sales, accouting; public Connection() { developer = new Developer(this); // initialize other state objects } public void open() { currentState.open(); public void close() { currentState.close(); public void update() { …} public void log() { …} Programming Design Patterns 11/28/2018

Programming Design Patterns Design Problem Design a light switch functionality How many states does it have? How many actions are possible? Now, modify/extend your code for a 3-way switch. two locations to control the same light bulb. Two states: on, off Two actions: turnOn, turnOff If you turnOn when the state is off, change the state to On If you turnOn when the state is on, don’t change the state. Do nothing Same for turnOff actions. Should have a light object, which implements an interface Device, that is passed by the Context class to the States Programming Design Patterns 11/28/2018