STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise2007006.

Slides:



Advertisements
Similar presentations
By : Atri Chatterjee Souvik Ghosh
Advertisements

GoF State Pattern Aaron Jacobs State(305) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Matt Klein 7/6/2009.  Behavioral Pattern  Intent  Allow an object to alter its behavior when its internal state changes. The object will appear to.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Component Patterns – Architecture and Applications with EJB copyright © 2001, MATHEMA AG Component Patterns Architecture and Applications with EJB JavaForum.
Zahra Moslehi AmirKabir University of Technology, Department of Computer Engineering & Information Technology Advanced design pattern Course Fall 2010.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
. Plab – Tirgul 12 Design Patterns. Design Patterns u The De-Facto Book on Design Patterns:
BehavioralCmpE196G1 Behavioral Patterns Chain of Responsibility (requests through a chain of candidates) Command (encapsulates a request) Interpreter (grammar.
HST 952 Computing for Biomedical Scientists Lecture 2.
Design Patterns I 1. Creational Pattern Singleton: intent and structure Ensure a class has one instance, and provide a global point of access to it 2.
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VI Composite, Iterator, and Visitor Patterns.
What Is a Factory Pattern?.  Factories are classes that create or construct something.  In the case of object-oriented code languages, factories construct.
Behavioral Patterns C h a p t e r 5 – P a g e 128 BehavioralPatterns Design patterns that identify and realize common interactions between objects Chain.
BDP Behavioral Pattern. BDP-2 Behavioral Patters Concerned with algorithms & assignment of responsibilities Patterns of Communication between Objects.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
02 - Behavioral Design Patterns – 2 Moshe Fresko Bar-Ilan University תשס"ח 2008.
1 GoF Template Method (pp ) GoF Strategy (pp ) PH Single User Protection (pp ) Presentation by Julie Betlach 6/08/2009.
Chapter 5 Implementing UML Specification (Part II) Object-Oriented Technology From Diagram to Code with Visual Paradigm for UML Curtis H.K. Tsang, Clarence.
1 Unit 5 Design Patterns: Design by Abstraction. 2 What Are Design Patterns?  Design patterns are: Schematic descriptions of design solutions to recurring.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Strategy Design Patterns CS 590L - Sushil Puradkar.
Unit 4 Object-Oriented Design Patterns NameStudent Number CAI XIANGHT082182A KYAW THU LINHT082238Y LI PENGFEIHT082220L NAUNG NAUNG LATTHT082195L PLATHOTTAM.
Structural Design Patterns
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
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.
Define an interface for creating an object, but let subclasses decide which class to instantiate Factory Method Pattern.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Define an interface for creating an object, but let subclasses decide which class to instantiate.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
Design Patterns By Mareck Kortylevitch and Piotreck Ratchinsky.
Behavioral Patterns1 Nour El Kadri SEG 3202 Software Design and Architecture Notes based on U of T Design Patterns class.
Chain of Responsibility A graphical user interface and a user that needs help; a security system with multiple sensors; a banking automated coin storage.
Design Patterns Introduction
State Design Pattern. Behavioral Pattern Allows object to alter its behavior when internal state changes Uses Polymorphism to define different behaviors.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Stéphane Ducasse 1 Strategy.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Singleton Pattern Presented By:- Navaneet Kumar ise
Applying the Principles Two Examples. Example 1 New Requirement It would be nice with a simple GUI “to see something” instead of just xUnit tests...
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
An object's behavior depends on its current state. Operations have large, multipart conditional statements that depend on the object's state.
The State Design Pattern A behavioral design pattern. Shivraj Persaud
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Design Patterns: Brief Examples
Software Design Patterns
Factory Patterns 1.
Introduction to Design Patterns
Behavioral Design Patterns
Software Design and Architecture
Software Design and Architecture
State pattern – A logical ‘Finite State Machine’
State Design Pattern 1.
Introduction to Behavioral Patterns (2)
DESIGN PATTERNS : State Pattern
State Pattern By the Group of Four.
Strategy Design Pattern
Software Design Lecture : 28.
State Design Pattern.
Presentation transcript:

STATE PATTERN Presented by Bharavi Mishra Bharavi Mishraise

Simple problem We have to automate a Chocolate machine. In this Chocolate machine,if any one wants to buy a chocolate, will drop a coin in machine and than push nob to get the chocolate.

State Diagram Out of Chocolate Has coin Chocolate Sold No coin Insert coin Eject coin Push nob Dispense Choco>0 Choco=0

General Class Diagram Test insertcoin(); turnnob(); ejectcoin(); choco public choco(int count) public void insertcoin() public void ejectcoin() public void turnnob() public void dispense()

General Solution public class choco { final static int sold_out=0; final static int sold_out=0; final static int no_quarter=1; final static int no_quarter=1; final static int has_quarter=2; final static int has_quarter=2; final static int sold=3; final static int sold=3; int state=sold_out; int state=sold_out; int count=0; int count=0; /** Creates a new instance of choco */ /** Creates a new instance of choco */ public choco(int count) { public choco(int count) { this.count=count; this.count=count; if(count>0){ if(count>0){ state=no_quarter; state=no_quarter; } }

Insert coin function public void insertcoin(){ if(state==has_quarter){ if(state==has_quarter){ System.out.println("u can,t insert another coin"); System.out.println("u can,t insert another coin"); } else if(state==no_quarter){ else if(state==no_quarter){ System.out.println("u inserted a coin"); System.out.println("u inserted a coin"); state = has_quarter; state = has_quarter; } else if(state==sold_out){ else if(state==sold_out){ System.out.println("u can't inserted a coin,machine is soldout"); System.out.println("u can't inserted a coin,machine is soldout"); } else if(state==sold){ else if(state==sold){ System.out.println("please wait,u have got one "); System.out.println("please wait,u have got one "); } }

Eject coin public void ejectcoin(){ if(state==has_quarter){ if(state==has_quarter){ System.out.println("coin returned"); System.out.println("coin returned"); state=no_quarter; state=no_quarter; } else if(state==no_quarter){ else if(state==no_quarter){ System.out.println("u have,t inserted a coin"); System.out.println("u have,t inserted a coin"); } else if(state==sold){ else if(state==sold){ System.out.println("Sorry,u have already got one"); System.out.println("Sorry,u have already got one"); } else if(state==sold_out){ else if(state==sold_out){ System.out.println("u can't eject, u have't inserted a coin"); System.out.println("u can't eject, u have't inserted a coin"); } }

Turn nob public void turnnob(){ if(state==has_quarter){ if(state==has_quarter){ System.out.println("u turned"); System.out.println("u turned"); state=sold; state=sold; dispense(); dispense(); } else if(state==no_quarter){ else if(state==no_quarter){ System.out.println("u turned but there is no coin"); System.out.println("u turned but there is no coin"); } else if(state==sold){ else if(state==sold){ System.out.println("turninf twice does,t get more then one"); System.out.println("turninf twice does,t get more then one"); } else if(state==sold_out){ else if(state==sold_out){ System.out.println("u turnned but no chokolate"); System.out.println("u turnned but no chokolate"); } }

Dispense public void dispense(){ if(state==has_quarter){ if(state==has_quarter){ System.out.println("no chocolate dispensed"); System.out.println("no chocolate dispensed"); } else if(state==no_quarter){ else if(state==no_quarter){ System.out.println("u must have to pay first"); System.out.println("u must have to pay first"); } else if(state==sold){ else if(state==sold){ System.out.println("a chocolate comes rooling out the sllot"); System.out.println("a chocolate comes rooling out the sllot"); count=count-1; count=count-1; if(count==0){ if(count==0){ System.out.println("sorry!here is no chocolate"); System.out.println("sorry!here is no chocolate"); state =sold_out; state =sold_out; }

Cont… else{ state=no_quarter; state=no_quarter; } } else if(state==sold_out){ else if(state==sold_out){ System.out.println("no chocolate dispensed"); System.out.println("no chocolate dispensed"); } } }

Test Class public class test { /** Creates a new instance of test */ /** Creates a new instance of test */ /** /** args the command line arguments args the command line arguments */ */ public static void main(String[] args) { public static void main(String[] args) { // TODO code application logic here // TODO code application logic here choco c1 = new choco(2); choco c1 = new choco(2); c1.insertcoin(); c1.insertcoin(); c1.turnnob(); c1.turnnob(); c1.ejectcoin(); c1.ejectcoin(); c1.insertcoin(); c1.insertcoin(); c1.turnnob(); c1.turnnob(); c1.insertcoin(); c1.insertcoin(); c1.turnnob(); c1.turnnob(); } }

Enhancement Out of Chocolate Has coin Chocolate Sold No coin Insert coin Eject coin Push nob Dispense Choco>0 Choco=0 Winner Push nob for winner Dispense Choco>0 Choco=0

Problem If we want to add one more state Winner. Than we must have to modify each and every function. That is violation of open closed principle. That is the base of oops.

Solution Use State Design Pattern instead of Traditional one. Use State Design Pattern instead of Traditional one.

Sold out Class ChocoMAchine Class public Chocomachine(int numbercho) public void ejectcoin() public void insertcoin() public void ejectcoin() public void setstate(state st) ….. ….. Test insertcoin(); turnnob(); ejectcoin(); State Interface public void insertcoin(); public void insertcoin(); public void ejectcoin(); public void ejectcoin(); public void turnnob(); public void turnnob(); public void dispense(); public void dispense(); Has coin Class No coin class Sold Class

Enhancement Test insertcoin(); turnnob(); ejectcoin(); State Interface public void insertcoin(); public void insertcoin(); public void ejectcoin(); public void ejectcoin(); public void turnnob(); public void turnnob(); public void dispense(); public void dispense(); Has coin Class Sold Class ChocoMAchine Class public Chocomachine(int numbercho) public void ejectcoin() public void insertcoin() public void ejectcoin() public void setstate(state st) ….. ….. Sold out Class No coin class Winner

State interface public interface state { public void insertcoin(); public void insertcoin(); public void ejectcoin(); public void ejectcoin(); public void turnnob(); public void turnnob(); public void dispense(); public void dispense(); }

Has coin Class public class Hasquarter implements state { Chocomachine ch1; Chocomachine ch1; /** Creates a new instance of Noquarter */ /** Creates a new instance of Noquarter */ public Hasquarter(Chocomachine ch1) { public Hasquarter(Chocomachine ch1) { this.ch1=ch1; this.ch1=ch1; } public void insertcoin(){ public void insertcoin(){ System.out.println("u can't insrt another coin"); System.out.println("u can't insrt another coin"); } public void ejectcoin(){ public void ejectcoin(){ System.out.println("coin returned"); System.out.println("coin returned"); ch1.setstate(ch1.getnoquarter()); ch1.setstate(ch1.getnoquarter()); } public void turnnob(){ public void turnnob(){ System.out.println("u turned "); System.out.println("u turned "); ch1.setstate(ch1.getsold()); ch1.setstate(ch1.getsold()); } public void dispense(){ public void dispense(){ System.out.println("no chocolate dispense"); System.out.println("no chocolate dispense"); }}

No coin class public class Noquarter implements state{ Chocomachine ch1; Chocomachine ch1; /** Creates a new instance of Noquarter */ /** Creates a new instance of Noquarter */ public Noquarter(Chocomachine ch1) { public Noquarter(Chocomachine ch1) { this.ch1=ch1; this.ch1=ch1; } public void insertcoin(){ public void insertcoin(){ System.out.println("u insrted a coin"); System.out.println("u insrted a coin"); ch1.setstate(ch1.gethasquarter()); ch1.setstate(ch1.gethasquarter()); } public void ejectcoin(){ public void ejectcoin(){ System.out.println("u have't inserted a coin"); System.out.println("u have't inserted a coin"); } public void turnnob(){ public void turnnob(){ System.out.println("u turned but here is no coin"); System.out.println("u turned but here is no coin"); } public void dispense(){ public void dispense(){ System.out.println("u must have to pay first"); System.out.println("u must have to pay first"); }}

Sold Class public class Sold implements state{ Chocomachine ch1; Chocomachine ch1; /** Creates a new instance of Noquarter */ /** Creates a new instance of Noquarter */ public Sold(Chocomachine ch1) { public Sold(Chocomachine ch1) { this.ch1=ch1; this.ch1=ch1; } public void insertcoin(){ public void insertcoin(){ System.out.println("Please wait,u have got one already"); System.out.println("Please wait,u have got one already"); } public void ejectcoin(){ public void ejectcoin(){ System.out.println("Sorry,u have turned yhe nob"); System.out.println("Sorry,u have turned yhe nob"); }

Cont.. public void turnnob(){ System.out.println(" turning twice does,t get u anoyher chocolate"); System.out.println(" turning twice does,t get u anoyher chocolate"); } public void dispense(){ public void dispense(){ ch1.release(); ch1.release(); if(ch1.getcount()>0){ if(ch1.getcount()>0){ ch1.setstate(ch1.getnoquarter()); ch1.setstate(ch1.getnoquarter()); } else{ else{ System.out.println("u must have to pay first"); System.out.println("u must have to pay first"); ch1.setstate(ch1.getsoldout()) ; ch1.setstate(ch1.getsoldout()) ; } }}

Sold out Class public class Soldout implements state { Chocomachine ch1; Chocomachine ch1; /** Creates a new instance of Soldout */ /** Creates a new instance of Soldout */ public Soldout(Chocomachine ch1) { public Soldout(Chocomachine ch1) { this.ch1=ch1; this.ch1=ch1; } public void insertcoin(){ public void insertcoin(){ System.out.println("u can,t inseart a coin,the machine is sold out"); System.out.println("u can,t inseart a coin,the machine is sold out"); } public void ejectcoin(){ public void ejectcoin(){ System.out.println("u can,t eject,u have,t inserted a coin"); System.out.println("u can,t eject,u have,t inserted a coin"); } public void turnnob(){ public void turnnob(){ System.out.println(" u turn but there is no chocolate"); System.out.println(" u turn but there is no chocolate"); } public void dispense(){ public void dispense(){ System.out.println("no chocolate dispense"); System.out.println("no chocolate dispense"); }}

ChocoMAchine Class public class Chocomachine { state soldoutstate; state soldoutstate; state soldstate; state soldstate; state hascoinstate; state hascoinstate; state nocoinstate; state nocoinstate; state st = soldoutstate; state st = soldoutstate; int count=0; int count=0; /** Creates a new instance of Chocomachine */ /** Creates a new instance of Chocomachine */ public Chocomachine(int numbercho) { public Chocomachine(int numbercho) { soldoutstate =new Soldout(this) ; soldoutstate =new Soldout(this) ; soldstate = new Sold(this); soldstate = new Sold(this); hascoinstate = new Hasquarter(this); hascoinstate = new Hasquarter(this); nocoinstate = new Noquarter(this); nocoinstate = new Noquarter(this); this.count=numbercho; this.count=numbercho; if(numbercho>0){ if(numbercho>0){ st=nocoinstate; st=nocoinstate; } }

Cont… public void insertcoin(){ public void insertcoin(){ st.insertcoin(); st.insertcoin(); } public void ejectcoin(){ public void ejectcoin(){ st.ejectcoin(); st.ejectcoin(); } public void turnnob(){ public void turnnob(){ st.turnnob(); st.turnnob(); st.dispense(); st.dispense(); } public void setstate(state st){ public void setstate(state st){ this.st=st; this.st=st; } public void release(){ public void release(){ System.out.println("A chocolate rooling out the slot"); System.out.println("A chocolate rooling out the slot"); if(count!=0){ if(count!=0){ count=count-1; count=count-1; } }

Cont.. public state gethasquarter(){ st=hascoinstate; st=hascoinstate; return (st); return (st); } public state getnoquarter(){ public state getnoquarter(){ st=nocoinstate; st=nocoinstate; return(st); return(st); } public state getsoldout(){ public state getsoldout(){ st=soldoutstate; st=soldoutstate; return(st); return(st); } public int getcount(){ public int getcount(){ return count; return count; } public state getsold(){ public state getsold(){ st=soldstate; st=soldstate; return (st); return (st); }

Test Class public class test { /** Creates a new instance of test */ /** Creates a new instance of test */ public test() { public test() { } /** /** args the command line arguments args the command line arguments */ */ public static void main(String[] args) { public static void main(String[] args) { // TODO code application logic here // TODO code application logic here Chocomachine choco=new Chocomachine(2); Chocomachine choco=new Chocomachine(2); choco.insertcoin(); choco.insertcoin(); choco.turnnob(); choco.turnnob(); choco.ejectcoin(); choco.ejectcoin(); choco.insertcoin(); choco.insertcoin(); choco.ejectcoin(); choco.ejectcoin();

Pattern name :- State pattern. State pattern. Class :- Behavioral Pattern. Behavioral Pattern. Intent :- Allow an object to alter its behavior Allow an object to alter its behavior when its internal state changes. The when its internal state changes. The object Will appear to change its class. object Will appear to change its class.

Also known as :- Object for state pattern. Object for state pattern.Motivation:- 1: State pattern is useful when there is an object that can be in one of several states, with different behavior in each state. 1: State pattern is useful when there is an object that can be in one of several states, with different behavior in each state. 2:To simplify operations that have large conditional statements that depend on the object’s state. 2:To simplify operations that have large conditional statements that depend on the object’s state.

As: if (myself = happy) then if (myself = happy) then { eatIceCream(); eatIceCream(); …. …. } else if (myself = sad) then { goToPub(); goToPub(); …. …. } else if (myself = ecstatic) then { dohelp(); dohelp(); …. …. }

Applicability:- An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state. An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state. Operations have large, multipart conditional statements that depend on the object’s state. This state usually represented by one or more constants. The State pattern puts each branch of the conditional in a separate class. Operations have large, multipart conditional statements that depend on the object’s state. This state usually represented by one or more constants. The State pattern puts each branch of the conditional in a separate class.

Structure Context State ConcreatState1 ContreateState2 ConcreateState3 Handle() State->Handle() Client

Participant:- Context::- Context::- 1-Provide interface for client. 1-Provide interface for client. 2-Maintain an instance of a concretestate subclass 2-Maintain an instance of a concretestate subclass that define current state. that define current state. State::- State::- Defines an interface for encapsulating the behavior Defines an interface for encapsulating the behavior associated with a particular state of the context associated with a particular state of the context ConcreteStateclass::- ConcreteStateclass::- Each subclass implements behavior associated with Each subclass implements behavior associated with a state of the context a state of the context

Collaboration:- A context may pass itself as an argument to the A context may pass itself as an argument to the State object handling the request. This lets the State object handling the request. This lets the State object access the context if necessary. State object access the context if necessary. Context delegates state-specific requests to the current ConcreteState object. Context delegates state-specific requests to the current ConcreteState object. Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don’t have to deal with the State objects directly. Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don’t have to deal with the State objects directly. Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances. Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances.

Consequences It localizes state-specific behavior and partitions behavior for different states. It localizes state-specific behavior and partitions behavior for different states. It makes state transitions explicit. It makes state transitions explicit. State objects can be shared. State objects can be shared.

Possible Issues If there are many different states that all need to have transition functions to one another, the amount of transition code required could be massive. If there are many different states that all need to have transition functions to one another, the amount of transition code required could be massive.Switch(State) case A: … case B: … etc…

Known Uses and Related Patterns Popular interactive drawing programs use the State pattern to perform specific operations based on which State(tool) is selected. Popular interactive drawing programs use the State pattern to perform specific operations based on which State(tool) is selected. The Flyweight (195) pattern explains when and how State objects can be shared. The Flyweight (195) pattern explains when and how State objects can be shared. State Objects are often Singletons(127). State Objects are often Singletons(127).

Thanks……