Design Patterns: State, Bridge, Visitor

Similar documents
Design Patterns: Template Method, Strategy, State, Bridge

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

(Refer Slide Time: 00:23)

Software Design and Analysis for Engineers

Design Patterns: Prototype, State, Composite, Memento

Design Patterns: Composite, Memento, Template Method, Decorator, Chain of Responsibility, Interpreter

Several patterns can be implemented elegantly using closures.

Lecture 10: building large projects, beginning C++, C++ and structs

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Implementing GUI context-sensitive help... ECE450 Software Engineering II. Implementing GUI context-sensitive help... Context-sensitive help

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Java Object Oriented Design. CSC207 Fall 2014

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

Chapter 1 Getting Started

CH. 2 OBJECT-ORIENTED PROGRAMMING

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Chapter 5 Object-Oriented Programming

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Compiler Design Spring 2017

Introduction to Programming Using Java (98-388)

16 Multiple Inheritance and Extending ADTs

Polymorphism Part 1 1

CSCI 355 LAB #2 Spring 2004

Introduction to Design Patterns

Inheritance, Polymorphism and the Object Memory Model

Lecture Topics. Administrivia

Introduction to Programming (Java) 4/12

CSCI 355 Lab #2 Spring 2007

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Object Orientated Analysis and Design. Benjamin Kenwright

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Use the scantron sheet to enter the answer to questions (pages 1-6)

Mutating Object State and Implementing Equality

Final exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)

Inheritance and Interfaces

Lecture Set 4: More About Methods and More About Operators

G52CPP C++ Programming Lecture 3. Dr Jason Atkin

What are the characteristics of Object Oriented programming language?

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Grammars and Parsing, second week

a correct statement? You need to know what the statement is supposed to do.

ITI Introduction to Computing II

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

About this exam review

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

ITI Introduction to Computing II

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

1 Shyam sir JAVA Notes

CS-202 Introduction to Object Oriented Programming

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Lecture 5: Methods CS2301

CSE 70 Final Exam Fall 2009

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

1.00 Lecture 4. Promotion

Main Topics. Study Tactics. Exam Structure, Roughly. Java Fundamentals. CISC 3120 Midterm Review Guide

CS/ENGRD 2110 SPRING 2018

Inheritance, Polymorphism, and Interfaces

CS 251 Intermediate Programming Methods and Classes

BM214E Object Oriented Programming Lecture 4

CS 251 Intermediate Programming Methods and More

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Zheng-Liang Lu Java Programming 45 / 79

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

First of all, it is a variable, just like other variables you studied

Derived and abstract data types. TDT4205 Lecture 15

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

1.00 Lecture 14. Exercise: Plants

Lecture Set 4: More About Methods and More About Operators

Anatomy of a Class Encapsulation Anatomy of a Method

Lecture 5: Inheritance

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

************ THIS PROGRAM IS NOT ELIGIBLE FOR LATE SUBMISSION. ALL SUBMISSIONS MUST BE RECEIVED BY THE DUE DATE/TIME INDICATED ABOVE HERE

Binghamton University. CS-140 Fall Dynamic Types

Discussion 1H Notes (Week 2, 4/8) TA: Brian Choi Section Webpage:

5. Defining Classes and Methods

Design Patterns Reid Holmes

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

QUIZ. What is wrong with this code that uses default arguments?

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Software Design and Analysis for Engineers

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Topic 7: Algebraic Data Types

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

Defining Classes and Methods

Lecture 3. Lecture

Transcription:

Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement finite-state machines. Outline for Week 14 I. State pattern II. Bridge III. Visitor Here s an example. An example: Horner's Rule A finite-state machine can be used to convert an ASCII string of characters representing a real number to its actual numerical value. The letters shown in the FSM stand for the following: c - current character s - sign of the number v - value of the number p - power Week 14 Object-Oriented Design and Development 1

Note that this FSM assumes that the string contains a valid floating point number that starts with an optional + or, has at least one digit, an optional decimal point, and any number (including 0) of digits before and after the decimal point. A value of 0 is returned if an invalid string is encountered. Table form of FSM: State/Input + or. digit other START INTEGER DECIMAL INTEGER ERROR INTEGER ERROR DECIMAL INTEGER END DECIMAL ERROR ERROR DECIMAL END Using switch statements, this FSM can be coded as follows: public class Parser { static double todouble(string s) { double sign = 1; // sign of number (either 1 or 1) double value = 0; // current value of the number double power = 0.1; // current power of 10 for // digits after decimal point int i = 0; final int START = 0; final int INTEGER = 1; final int DECIMAL = 2; final int ERROR = 3; int state = START; char ch; //current character in string while (state!= ERROR && i < s.length()) { ch = s.charat(i++); switch (state) { case START: if (ch ==. ) state = DECIMAL; else if (ch == ) { sign = 1.0; state = INTEGER; else if (ch == + ) CSC/ECE 517 Lecture Notes 2017 Edward F. Gehringer 2

state = INTEGER; else if (Character.isDigit(ch)) { value = ch 0 ; state = INTEGER; else state = ERROR; break; case INTEGER: if (ch ==. ) state = DECIMAL; else if (Character.isDigit(ch)) value = 10.0 * value + (ch 0 ); else { value = 0.0; state = ERROR; break; case DECIMAL: if (Character.isDigit(ch)) { value += power * (ch 0 ); power /= 10.0; else { value = 0.0; state = ERROR; break; default: System.out.println("Invalid state: " + state); return sign * value; public static void main(string[] args) { if (args.length == 1) System.out.println(toDouble(args[0])); This FSM can be represented more elegantly by the State pattern. How can we code State in a more o-o fashion? Hint: We can make State an interface! Each state will implement this interface. Horner s Rule: To use the State pattern for Horner s rule, the first step is to define a State interface. Consider the table form of the FSM. The rows of the table represent the different states. Week 14 Object-Oriented Design and Development 3

The columns of the table represent the different behaviors of each state. Therefore, what methods should be defined in the State interface? Well, what do we need to test for each state? Submit your State interface here. public interface State { void onpoint(); ; ; ; void onother(); How should the States be defined? class implements { class implements { class implements { In Java, we can define a class within another class. This is called an inner class. Thus, our States can be defined as inner classes of Parser. Here is the code for the Parser class, minus its inner classes: public class Parser { private final State start = new Start(); private final State integer = new Integr(); private final State decimal = new Decimal(); private State state = start; double sign = 1; // sign of number (either 1 or -1) double value = 0; // current value of the number double power = 0.1; // current power of 10 for // digits after decimal point char ch; //current character in string double todouble(string s) { int i = 0; while (i < s.length()) { CSC/ECE 517 Lecture Notes 2017 Edward F. Gehringer 4

ch = s.charat(i++); if (ch == '.') state.onpoint(); else if (ch == '+') state.onplus(); else if (ch == '-') state.onminus(); else if (Character.isDigit(ch))state.onDigit(); else state.onother(); return sign * value; public static void main(string[] args) { System.out.println(new Parser().toDouble("-914.334")); Exercise: Depending on your row, choose one method to implement in all three classes. Submit your code here. void onminus(); void onplus(); void ondigit(); void onother(); If an illegal character is found, throw a NumberFormatException. State Intent: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Problem: A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterized by large and numerous case statements that vector flow of control based on the state of the application. Solution: Define a set of State objects. Defer the implementation of the different methods to the State objects. The client changes its state from time to time. Implementation: Define a context class to present a single interface to the outside world. Define a State abstract base class. Week 14 Object-Oriented Design and Development 5

Represent the different states of the state machine as derived classes of the State base class. Define state-specific behavior in the appropriate State derived classes. Maintain a pointer to the current state in the context class. To change the state of the state machine, change the current state pointer. State vs. Strategy Recall the Strategy pattern from online Week 6 (Lecture 9). In this case, you need to choose an algorithm for a task depending on some parameter of the situation. For example, consider quadrature (numerical integration) again. Each time you calculate the area of a region, you need to know what the function is that you are calculating the region underneath. Or consider how to open, read/write from, and close different kinds of files. The definition of Strategy from HFDP is, 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. Let s provide a definition of Strategy in the format that we have used before. Strategy Intent: To decouple algorithms from the objects that use them. Problem: We need to write code that will work with objects that behave differently. We don t want the host class to know how the objects behave, but just to invoke the different behaviors when appropriate. CSC/ECE 517 Lecture Notes 2017 Edward F. Gehringer 6

Solution: Create different classes, each of which defines the behavior for one type of object. Then, when the host class wants to invoke a certain behavior, it merely calls a method of the appropriate behavior class. Implementation: The behavior classes are usually subclasses of a class that defines an abstract behavior. Then the host class invokes a method of the abstract behavior class, and what is really called is a method of the concrete behavior class. Strategy allows clients to change algorithms at run time by using a different strategy object. This basically lets them appear to change class at run time. Hmmm that s interesting. Strategy lets objects appear to change class. Isn t that what State does? How can we tell the difference between Strategy and State? Bridge Now, let s look at the class diagram for the State pattern (for example, at http://www.dofactory.com/patterns/patternstate.aspx). Note that the Context object holds a reference to an abstract class. This is the abstract class from which the concrete states are derived. It turns out that the same structure is valuable for implementing drivers. What s a driver? Drivers are generally used by various applications. Consider a printer driver, for example. There is a driver for a particular printer for each OS. Many different applications can use that printer, providing that the right driver is present. This is an example of the bridge pattern. We have various abstractions (the applications) and various implementations (the drivers). If the applications aren t in a hierarchy, the class diagram for Bridge is exactly the same as the class diagram for State. But often, the abstractions are in a hierarchy. HFDP gives the example of televisions and remotes. TVs have behavior in common, Week 14 Object-Oriented Design and Development 7

and so do remotes. If they re universal remotes, they can be used by lots of different kinds of TVs. This leads to this UML diagram. What are the advantages of Bridge? Here s another example, from StackOverflow: Suppose you have shapes, each of which can be various colors. Would you subclass Shape with Rectangle and Circle Shape Rectangle Circle and then subclass again for color: Shape Rectangle Circle BlueRectangle RedRectangle BlueCircle RedCircle The Bridge pattern says to represent this as Shape Color Rectangle Circle Red Blue CSC/ECE 517 Lecture Notes 2017 Edward F. Gehringer 8

This is another way of preferring composition over inheritance. (What was another example we saw of that?) Bridge Intent: To decouple interfaces from the implementations that use them. Problem: We need to construct an interface that may change (or be added to), and several implementations of that interface. We don t want to have to have each implementation implement each interface. Solution: Use a hierarchy of interfaces, and a hierarchy of implementations. The implementations code to a single abstract interface. The other interfaces are written in terms of the abstract interface. Implementation: Use two class hierarchies, where the interface hierarchy has-an abstract implementation. Now finish this example of the Bridge pattern. Visitor Remember our discussion of overloading vs. overriding, from Lecture 16? At that time, we said, In summary, the compiler decides which overloaded method to call by looking at the declared type of the object being sent the message and the declared types of the arguments to the method call. The method is chosen at runtime by dynamic method invocation using the actual value of the object being sent the message. The actual classes of the arguments to the method call do not play a role. This is very different from a language like CLOS, which uses the actual types of the arguments to decide which method to execute. Suppose we did want the classes of the arguments to be used to determine which method to call. Week 14 Object-Oriented Design and Development 9

My favorite example is double-dispatching in arithmetic expressions. If you add an integer and a floating-point number, what type should the result be? Assuming you have a Fraction class, if you add an integer and a fraction, what type should the result be? If you add a floating-point number and a complex number, what type should the result be? Should either the floating-point or complex number be able to be the receiver? Should either be able to be the argument? So, the method called should depend both on the class of the receiver and the class of the argument. How do we achieve this effect? Let s say that we implement the Sum method in all numeric classes Integer, Floating Point, Fraction, and Complex. So, if we re performing an addition, we invoke the Sum method of the class. Now, this Sum method knows that what it does actually depends on the class of its argument. How does it achieve this effect? This method, e.g., in the Complex class, is called something like, SumFromFloatingPoint. What does it do? What does it return? OK, suppose that we have the four numeric classes mentioned above. How many Sum methods do we need altogether? Here is how Visitor is structured. CSC/ECE 517 Lecture Notes 2017 Edward F. Gehringer 10

Define an interface or abstract class Visitor. Visitor contains a visit() method, which is implemented in each subclass of Visitor. (In our example, these are the sumfrom methods.) These methods are invoked from subclasses of the Element hierarchy. Each one of these classes has an accept() method, which takes an object of the Visitor hierarchy as a parameter. Each descendant of the Element class implements accept()by calling the visit() method on the Visitor object it was passed, with this as the only parameter. To perform an operation, the client creates a Visitor object, and calls accept()on the Element object, passing the Visitor object. The Visitor pattern can be used to avoid tight coupling, as Bob Martin explains. Can you think of another example of Visitor? What s the example given in the text for Visitor? Submit here. Week 14 Object-Oriented Design and Development 11