State Design Pattern. Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

By : Atri Chatterjee Souvik Ghosh
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
March 2004Object Oriented Design1 Object-Oriented Design.
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
Unit 191 Recursion General Algorithm for Recursion When to use and not use Recursion Recursion Removal Examples Comparison of the Iterative and Recursive.
Client/Server example. Server import java.io.*; import java.net.*; import java.util.*; public class PrimeServer { private ServerSocket sSoc; public static.
Java sockets. From waiting.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
SELECTION CSC 171 FALL 2004 LECTURE 8. Sequences start end.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Java Review 3 Rem Collier. Java Wrapper Classes In Java, the term wrapper class commonly refers to a set of Java classes that “objectify” the primitive.
1 First app – simplechat1 Reminder: what’s the point?  To build on ocsf framework.  Simple requirements: echo all messages to all clients.  Use only.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
Saravanan.G.
JAVA PROGRAMMING PART II.
CSC3170 Introduction to Database Systems
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Georgia Institute of Technology Speed part 3 Barb Ericson Georgia Institute of Technology May 2006.
CS 350 – Software Design Template Method Pattern Let’s look at two objects public class Coffee { public void prepareRecipe() { public void prepareRecipe()
Programming Progamz pls. Importance VERY IMPORTANT.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
CS1101: Programming Methodology Recitation 3 – Control Structures.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
Interfaces. –An interface describes a set of methods: no constructors no instance variables –The interface must be implemented by some class. 646 java.
ILM Proprietary and Confidential -
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
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.
1 StringTokenization Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples.
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
FOR LOOP WALK THROUGH public class NestedFor { public static void main(String [] args) { for (int i = 1; i
LOGO 형식언어와 오토마타 컴퓨터 공학부 4 학년 서정태
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise
CS 121 – Intro to Programming:Java - Lecture 12 Announcements New Owl assignment up soon (today?) For this week: read Ch 8, sections 0 -3 Programming assignment.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Staples are our staple Building upon our solution.
Methods CSC 171 FALL 2001 LECTURE 3. History The abacus.
Reading Parameters CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D.
Methods Matthew Harrison. Overview ● There are five main aspects of methods... ● 1) Modifiers – public, private ● 2) Method Name ● 3) Parameters ● 4)
Threads in Java Two ways to start a thread
Sum of natural numbers class SumOfNaturalNumbers {
CS1101: Programming Methodology Recitation 7 – Exceptions
Accessing Files in Java
Operators Laboratory /11/16.
null, true, and false are also reserved.
Stack Memory 2 (also called Call Stack)
Interfaces and Constructors
Chapter Four: DFA Applications
class PrintOnetoTen { public static void main(String args[]) {
Exceptions.
Software Design Lecture : 39.
Barb Ericson Georgia Institute of Technology May 2006
Exceptions.
State Design Pattern.
Presentation transcript:

State Design Pattern

Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors for different states Implementation of Replace conditional with Polymorphism

When to use STATE pattern ? State pattern is useful when there is an object that can be in one of several states, with different behavior in each state. To simplify operations that have large conditional statements that depend on the object ’ s state. if (myself = happy) then { eatIceCream(); …. } else if (myself = sad) then { goToPub(); …. } else if (myself = ecstatic) then { ….

Example MyMoodMoodState doSomething() madangryhappy doSomething() state variable Client doSomething()

State Structure Allow a object to alter its behavior when its internal state changes.

// Not good: unwieldy "case" statement class CeilingFanPullChain { private int m_current_state; public CeilingFanPullChain() { m_current_state = 0; } public void pull() { if (m_current_state == 0) { m_current_state = 1; System.out.println(" low speed"); } else if (m_current_state == 1) { m_current_state = 2; System.out.println(" medium speed"); } else if (m_current_state == 2) { m_current_state = 3; System.out.println(" high speed"); } else { m_current_state = 0; System.out.println(" turning off"); } public class StateDemo { public static void main(String[] args) { CeilingFanPullChain chain = new CeilingFanPullChain(); while (true) { System.out.print("Press "); get_line(); chain.pull(); } static String get_line() { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)) ; String line = null; try { line = in.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return line; }

class CeilingFanPullChain { private State m_current_state; public CeilingFanPullChain() { m_current_state = new Off(); } public void set_state(State s) { m_current_state = s; } public void pull() { m_current_state.pull(this); } interface State { void pull(CeilingFanPullChain wrapper); } class Off implements State { public void pull(CeilingFanPullChain wrapper) { wrapper.set_state(new Low()); System.out.println(" low speed"); } class Low implements State { public void pull(CeilingFanPullChain wrapper) { wrapper.set_state(new Medium()); System.out.println(" medium speed"); } class Medium implements State { public void pull(CeilingFanPullChain wrapper) { wrapper.set_state(new High()); System.out.println(" high speed"); } class High implements State { public void pull(CeilingFanPullChain wrapper) { wrapper.set_state(new Off()); System.out.println(" turning off"); }

public class StateDemo { public static void main(String[] args) { CeilingFanPullChain chain = new CeilingFanPullChain(); while (true) { System.out.print("Press "); get_line(); chain.pull(); } static String get_line() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; String line = null; try { line = in.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return line; }

State Design Pattern

Alarm Clock State Machine Clock State: time, alarmTime Clock Inputs: setTime(), setAlarmTime(), alarmOn(), alarmOff(), snooze()