CSC/ECE 517 Fall 2012/ch2a 2w21 ap: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(189 intermediate revisions by 2 users not shown)
Line 1: Line 1:
Design patterns are convenient ways of reusing object-oriented code between projects and between programmers. The idea behind design patterns is to write down and catalog common interactions between objects that programmers have frequently found useful.
[http://en.wikipedia.org/wiki/Design_pattern Design patterns] are convenient ways of reusing object-oriented code between projects and between programmers. The idea behind design patterns is to write down and catalog common interactions between objects that programmers have frequently found useful.
The design patterns are divided into creational, structural and behavioral.
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.


__TOC__
__TOC__


=Behavioral Patterns=
=Behavioral Patterns=
These patterns help you to define the communication between objects in your system and also specify how the flow is controlled in a complex program.
[http://sourcemaking.com/behavioral_patterns][http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm][http://en.wikipedia.org/wiki/Behavioral_pattern Behavioral patterns] help you to define the communication between objects in your system and also specify how the flow is controlled in a complex program. These patterns are concerned with interactions between the objects. The interactions between the objects should be such that they can talk to each other and still be loosely coupled. This helps in avoiding dependencies and hard-coding.


=State Pattern=
=State Pattern=
State pattern is a behavioral software design pattern where behavior of any object depends upon current state of the object.  
[http://sourcemaking.com/design_patterns/state]
 
[http://en.wikipedia.org/wiki/State_pattern State pattern] is a behavioral software design pattern where behavior of any object depends upon current state of the object. A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state.
If an object has multiple states and corresponding behaviors, the class becomes too complex with numerous conditional statements if all the transitions are included as the functions of the same class. Also, it becomes difficult to incorporate more states in the same structure.
If an object has multiple states and corresponding behaviors, the class becomes too complex with numerous conditional statements if all the transitions are included as the functions of the same class. Also, it becomes difficult to incorporate more states in the same structure.


Therefore, to make the code more clean and modular, only state is included as a property of the object and behavior for each transition is encapsulated in the separate class. When the object’s internal state changes, its behavior is changed dynamically. Object appears to change its class.
Therefore, to make the code more clean and modular, only state is included as a property of the object and behavior for each transition is encapsulated in the separate class. When an object's internal state changes, its behavior is changed dynamically. Object appears to change its class.  


Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.


=Examples=
We should use the State pattern in the following scenario:
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state
*Operations have multiple conditional statements that depend on the object's state. The State pattern puts each branch of the conditional statement in a separate class.


=Structure=
There is a context class which communicates with the outside world. This class maintains the state of the corresponding object. An abstract state class is defined which is then derived by individual state classes. Context class is also called as Wrapper class.


//class diagram:
A few scenarios in which the state pattern can be used:
*Consider an implementation of XOR gate used in logic. XOR gate outputs 1 when both the inputs are 1 or both the inputs are 0. It outputs 0 when one input is 0 and one input is 1.
Application of state pattern for XOR gate:
 
Consider two states, ZERO and ONE.


State transition logic can be defined either in the wrapper class or in each individual state subclass. If it is included in wrapper class, structure becomes static, i.e., we can’t dynamically add new states to the structure. On the other hand, if it is included in each individual class, coupling increases.
If the system is initially in state ZERO:<br>


=Finite State Machine=
If the input message is 0, system goes into state ONE.
[[File:fsm.png|thumb|Finite State Machine]]
There are two approaches which are commonly used:<br>
1. Table based approach:<br>
This approach lists all the transitions as a function of the current state and input message. This approach works well when finite state machine is not too complex.<br>
2. Pattern based approach:<br>
In this approach, a conditional logic is used for transitions.


=Example=
Consider an implementation of XOR gate used in logic. XOR gate outputs 1 when both the inputs are 1 or both the inputs are 0. It outputs 0 when one input is 0 and one input is 1.
Application of state pattern for XOR gate:
Consider two states, ZERO and ONE.
If the system is initially in state ZERO:
if the input message is 0, system goes into state ONE.
If the input message is 1, state does not change.
If the input message is 1, state does not change.


If system is initially in state ONE:
If system is initially in state ONE:<br>
if the input message is 0, system goes into state ZERO.
 
If the input message is 0, system goes into state ZERO.
 
If the input message is 1, state of the system does not change.
If the input message is 1, state of the system does not change.
We can use state pattern to implement this example with two states state ZERO and state ONE. There are two input signals input_zero and input_one.
*[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]A bank account can change from an open account to a closed account and back to an open account again. The behavior of the two types of accounts is different.
*A chocolate vending machine can have states like waiting for coins, has coin, sold and sold out. There are actions performed for transitioning among the states like insert coins, dispense chocolate and return coin.
*[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]A simplified version of the Post Office Protocol used to download e-mail from a mail server. The code can be in states QUIT, HAVE_USER_NAME, START and AUTHORIZED and actions for transitioning between these states can be USER username, PASS password, LIST <message number>, RETR <message number> and QUIT.
=Structure=
[[File:genclass.png]]
<br>
[http://sourcemaking.com/design_patterns/state]
The diagram above shows the class diagram for State Pattern Implementation. There is a Context class which communicates with the outside world. This class maintains the state of the corresponding object. It can have a number of internal states. The Context class is also called as Wrapper class. An interface State defines a common interface for all the concrete states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time.
State transition logic can be defined either in the wrapper class or in each individual state subclass. If it is included in wrapper class, structure becomes static, i.e., we can’t dynamically add new states to the structure. On the other hand, if it is included in each individual class, it results in increased coupling.


//FINITE STATE MACHINE diagram FOR THIS EXAMPLE:
=A Real Life Example=
==Scenario==
Consider an example of a bulb which works in three modes, namely, Off, dim and normal. Initially, the bulb is in off state. When we turn the switch, it glows and goes into dim state. If we turn the switch again, it goes into normal state. It again goes into off state on turning the switch.


==A Possible Inefficient Java Implementation==
package patterns;
class LightStateContext {
    private int currentState;
    public LightStateContext() {
      currentState = 0;
    }
    public void turnSwitch(){
        if (currentState == 0){
          currentState = 1;
          System.out.println("change to dim state.");
        } else if (currentState == 1){
          currentState = 2;
          System.out.println("change to normal state.");
        } else if (currentState == 2){
          currentState = 0;
          System.out.println("change to off state.");
        }
    }
}
public class InefficientCodeDemo{
    public static void main(String[] args) {
      LightStateContext context = new LightStateContext();
          while (true) {
            context.turnSwitch();
          }
    }
}


An inefficient Java implementation:
The method turnSwitch acts as finite state machine for this scenario. It contains the conditional logic for state transitions. A lot of 'if else' statements make the code unnecessarily complex.
package patterns;
Also, to add another state for the bulb, we need to change the original LightStateContext class which makes this code inefficient and difficult to extend.


class FanStateContext {
==A Better Solution==
private int currentState;


public FanStateContext() {
A better solution can be provided using the state pattern. We can clearly identify the three states of the bulb, off, dim and normal. We can also formulate the logic for finite state machine.
currentState = 0;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.
}
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.


public void turnSwitch(){
The finite state machine for the states can be seen below.<br>
if (currentState == 0){
currentState = 1;
System.out.println("change to dim state.");
} else if (currentState == 1){
currentState = 2;
System.out.println("change to normal state.");
} else if (currentState == 2){
currentState = 0;
System.out.println("change to off state.");
}
}
}


[[File:fsm_resize.png]]


public class InefficientCodeDemo{
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.<br>
public static void main(String[] args) {
FanStateContext context = new FanStateContext();
while (true) {
            context.turnSwitch();
        }
}
}


Why is this implementation inefficient?
[[File:class_resize.png]]
TODO : add


=A Java implementation using the state pattern=
==Steps to Implement State Pattern==
1.dsfsdfds
#Identify the states and define values for each state (typically constants)  
2.dfsdf
#Create an instance variable that holds the current state.
3.sfsdf
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.
We go about implementing the state pattern in the following way:
#Create a class that acts as the state machine.
1. Identify the states and define values for each state (typically constants)  
#For each state, create a class which contains system behavior for that state and implements State.
2. Create an instance variable that holds the current state.
3. Identify all the actions that can occur in the system and find out all the actions that can cause state transition.
4. Create a class that acts as the state machine.
5. For each action, create a method that uses conditional statements to determine what behavior is appropriate in each state. You can also transition to another state in the conditional statement.


Let us see an example that shows an efficient implementation using the state pattern.  
==Java Implementation Using State Pattern==
#Class LightStateContext acts as finite state machine for this example. This class contains the state variable 'currentState'. It includes the action 'turnSwitch' and a method 'setCurrentState' to set the state of the bulb when turnSwitch is called.
# State interface contains turnSwitch method which is called by the context class.
# A class is created for each individual state. These classes implement the State interface and turnSwitch method of State interface is defined by these classes.
package patterns;
class LightStateContext {
    private State currentState;
    public LightStateContext() {
      currentState = new OffState();
    }
    public State getCurrentState() {
      return currentState;
    }
    public void setCurrentState(State currentState) {
      this.currentState = currentState;
    }
    public void turnSwitch(){
      currentState.turnSwitch(this);
    }
}
interface State{
    void turnSwitch(LightStateContext context);
}
class OffState implements State{
    @override
    public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new DimState());
      System.out.println("change to dim state.");
    }
}
class DimState implements State{
    @Override
    public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new NormalState());
      System.out.println("change to normal state.");
    }
}
class NormalState implements State{
@Override
    public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new OffState());
      System.out.println("change to off state.");
    }
}
public class StatePatternDemo {
    public static void main(String[] args) {
    LightStateContext context = new LightStateContext();
    while (true)
      context.turnSwitch();
    }
}


The output for the above program is:


package patterns;
change to dim state.<br>
change to normal state.<br>
change to bright state.<br>
change to off state.<br>


class FanStateContext {
and so on till the program terminates.
private State currentState;


public FanStateContext() {
==Ruby Implementation Using State Pattern==
currentState = new OffState();
The State Pattern implementation using Ruby for the same bulb scenario mentioned above is seen below.
}


public State getCurrentState() {
#Module State contains methods to initialize states, delete states, check whether a state exists and a method for transitions of the states.
return currentState;
#This module is included by Context class which acts as finite state machine for this example.
}
#Input signal for each state is the 'turnswitch' method. For each state, turnswitch method is defined in the Context class.
#When the turnswitch method for any context is called, turnswitch method for the current state is executed.
#Context class also includes a method reset which resets the current context into Off state.


public void setCurrentState(State currentState) {
[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html]
this.currentState = currentState;
}
public void turnSwitch(){
currentState.turnSwitch(this);
}
}


interface State{
module State
void turnSwitch(FanStateContext context);
    class StateInitError < Exception; end
}
    class StateSetError < Exception; end
    def with_key(key, ex, &b)
      if (@s_states.has_key?(key))
          yield b
      else
          raise(ex, "No such state `#{key}'", caller)
      end
    end
    def accept_states(*states)
      @s_states  = {}
      @s_initial = @s_current = states[0]
      states.each { |s| @s_states[s] = nil }
    end
    def reject_states(*states)
      states.each { |s|
          @s_states.delete(s)
          if (@s_current == s)
            if (@s_initial == s)
                @s_current = nil
            else
                @s_current = @s_initial
            end
          end
      }
    end
    def transition_to(s)
      with_key(s, StateSetError) {
          if (@s_states[s])
            @s_states[s].call
          end
          @s_current = s
      }
    end
    def state(s=nil, &b)
      return @s_current if (s.nil?)
      with_key(s, StateInitError) {
          if (block_given?)
            @s_states[s] = b
          if (@s_initial == s)
            transition_to(s)
          end
          else
          transition_to(s)
          end
      }
    end
end
########
class Context
    include(State)
    def initialize()
      accept_states(:offstate, :dimstate, :normalstate)
      state(:offstate) {
          def turnswitch
            puts("starting the bulb")
            transition_to(:dimstate)
          end
      }
      state(:dimstate) {
          def turnswitch
            puts("turning to normal")
            transition_to(:normalstate)
          end
      }
      state(:normalstate) {
          def turnswitch
            puts("switch off the bulb")
            transition_to(:offstate)
          end
      }
    end
    def reset()
      puts("resetting outside a state")
      transition_to(:offstate)
    end
end
c = Context.new
c.turnswitch # start the bulb state:dimstate
c.turnswitch    # change to state:normalstate
c.turnswitch    # change to state:offstate
c.reset      # reseting outside a state changes to state:offstate
p c.state    # print current state


class OffState implements State{
The output for the above is as seen below.
@Override
public void turnSwitch(FanStateContext context) {
context.setCurrentState(new DimState());
System.out.println("change to dim state.");
}
}


class DimState implements State{
starting the bulb<br>
@Override
turning to normal<br>
public void turnSwitch(FanStateContext context) {
switch off the bulb<br>
context.setCurrentState(new NormalState());
resetting outside a state<br>
System.out.println("change to normal state.");
offstate<br>
}
}


class NormalState implements State{
=Another example in Java using the state pattern=
@Override
public void turnSwitch(FanStateContext context) {
context.setCurrentState(new OffState());
System.out.println("change to off state.");
}
}


public class StatePatternDemo {
Consider an implementation of XOR gate used in logic. XOR gate outputs 1 when both the inputs are 1 or both the inputs are 0. It outputs 0 when one input is 0 and one input is 1.
public static void main(String[] args) {
 
FanStateContext context = new FanStateContext();
Application of the state pattern for XOR gate is as follows.
while (true)  
 
            context.turnSwitch();
Consider two states, ZERO and ONE. <br>
       
 
}
1. If the system is initially in state ZERO:<br>
}
-If the input message is 0, state does not change.<br>
-If the input message is 1, system goes into state ONE.<br>
 
2. If system is initially in state ONE:<br>
-If the input message is 0, state does not change.<br>
-If the input message is 1, system goes into state ZERO.<br>
 
The finite state machine below describes the state transitions on performing the various actions.
 
[[File:fsm_correct.png]]
 
The code for implementing this scenario using the state pattern is seen below.
 
package patterns;
class XOR{
    private State current_state;
    public XOR(){
      current_state = new Zero();
    }
    public void set_state(State s){
      current_state = s;
    }
    public void input_zero(){
      current_state.input_zero(this);
    }
    public void input_one(){
      current_state.input_one(this);
    }
}
//State base interface.
interface State{
    void input_zero(XOR wrapper);
    void input_one(XOR wrapper);
}
//class for state ZERO
class Zero implements State {
    @Override
    public void input_zero(XOR wrapper){
      System.out.println("New state : ZERO");
      wrapper.set_state(new Zero());
    }
    @Override
    public void input_one(XOR wrapper) {
      System.out.println("New state : ONE");
      wrapper.set_state(new One());
    }
}
//class for state ONE
class One implements State{
    @Override
    public void input_zero(XOR wrapper){
      System.out.println("New state : ONE");
      wrapper.set_state(new One());
    }
    @Override
    public void input_one(XOR wrapper){
      System.out.println("New state : ZERO");
      wrapper.set_state(new Zero());
    }
}
public class XorStateDemo {
    public static void main(String args[]){
      XOR gate = new XOR();
      int num = 1;  //get input from user
      if (num == 0)
          gate.input_zero();
      if (num == 1)
          gate.input_one();
    }
}
 
The output for the above program is,
New state : One
 
Thus from the initial state zero on the action input_one, the current state changes to one.


=Advantages=
=Advantages=
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]
Advantages of the state pattern can be summarized as:
Advantages of the state pattern can be summarized as:
1.  One object for one state. By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.
#One object for one state.  
2. Easy to entend
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.
#If the state pattern is implemented correctly, the code becomes easy to extend.
 
Let us assume we are asked to show that when the bulb is in the normal state and we turn the switch the bulb glows bright. To incorporate this kind of change we need to just do the following:
 
1. Add a new BrightState that implements the State interface
 
class BrightState implements State{
  @Override
    public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new OffState());
        System.out.println("change to off state.");
    }
}
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState
 
context.setCurrentState(new BrightState());


Let us consider that we have to add
The finite state machine that depicts this requirement by adding a new state is as seen below.


=Limitations=
[[File:after_resize.png]]
1. Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.
2. Becomes too heavy when Finite State Machine is not that complex.  


=State Pattern Vs Strategy Pattern=
=Limitations=  
Strategy pattern is another behavioral software design pattern which separates the behavioral algorithms from the object. Each algorithm is encapsulated in a different class. Depending upon the properties of the current object, decision of invoking an algorithm is taken at runtime.
[https://docs.google.com/a/ncsu.edu/viewer?a=v&q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&hl=en&gl=us&pid=bl&srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&pli=1]
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.
#Becomes too heavy when Finite State Machine is not that complex.


Main difference between the state pattern and strategy pattern is in strategy pattern, once a decision is made to invoke a particular algorithm, it is not possible to change it. Whereas in state pattern, transition between states occurs at runtime.
=Strategy Pattern Vs State Pattern=
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]A [http://en.wikipedia.org/wiki/Strategy_pattern Strategy pattern] is another behavioral software design pattern which separates the behavioral algorithms from the object. Each algorithm is encapsulated in a different class. Depending upon the properties of the current object, decision of invoking an algorithm is taken at runtime.


In state pattern, decision of which state to invoke depends only on one variable.  
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.
#The patterns differ in their intent. In a strategy pattern, the client specifies the strategy object that the client is composed with. There is a strategy object that is most appropriate for the context object. For example, Two sorting algorithms (Merge Sort and Quick sort) are implemented and the client can select either of the algorithms for sorting a list. In a state pattern, we have a set of behaviors encapsulated in state objects, at any time the context is delegating to one of those states. The current state changes with every action to reflect the internal state of the context. The client usually knows very little about the state objects.
#In a strategy pattern, once a decision is made to invoke a particular algorithm, it is not possible to change it. Whereas in state pattern, transition between states occurs at runtime.
#In state pattern, decision of which state to invoke depends only on one variable.
#We can say that state pattern is a type of strategy pattern where each state represents a different behavioral algorithm for the object in context.
A class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, and/or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed.
A state pattern can be used for implementing a drawing program. The program has many tools like pointer, fill shape which at any point in time can act as one of several tools. Instead of switching between multiple objects, the code maintains an internal state representing the tool currently in use.


We can say that state pattern is a type of strategy pattern where each state represents a difference behavioral algorithm for the object in context.
=Conclusion=
The State pattern can be used to replace to replace many ifs or switch statements. Thus inconsistent states can be avoided since state changes occur using just the one state object. Code becomes more understandable and maintainable. There are a few disadvantages of using the state pattern but the advantages outweigh the disadvantages.  


=References=
=References=
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]
#[http://sourcemaking.com/design_patterns/state State Pattern]
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]
#[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html Ruby Implementation of Bulb Example]
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&hl=en&gl=us&pid=bl&srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&pli=1 Limitations of State Pattern]
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]
=Further References=
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html

Latest revision as of 20:14, 3 November 2012

Design patterns are convenient ways of reusing object-oriented code between projects and between programmers. The idea behind design patterns is to write down and catalog common interactions between objects that programmers have frequently found useful. The design patterns are divided into creational patterns, structural patterns and behavioral patterns.

Behavioral Patterns

[1][2]Behavioral patterns help you to define the communication between objects in your system and also specify how the flow is controlled in a complex program. These patterns are concerned with interactions between the objects. The interactions between the objects should be such that they can talk to each other and still be loosely coupled. This helps in avoiding dependencies and hard-coding.

State Pattern

[3] State pattern is a behavioral software design pattern where behavior of any object depends upon current state of the object. A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. If an object has multiple states and corresponding behaviors, the class becomes too complex with numerous conditional statements if all the transitions are included as the functions of the same class. Also, it becomes difficult to incorporate more states in the same structure.

Therefore, to make the code more clean and modular, only state is included as a property of the object and behavior for each transition is encapsulated in the separate class. When an object's internal state changes, its behavior is changed dynamically. Object appears to change its class.

Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.

Examples

We should use the State pattern in the following scenario:

  • When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state
  • Operations have multiple conditional statements that depend on the object's state. The State pattern puts each branch of the conditional statement in a separate class.


A few scenarios in which the state pattern can be used:

  • Consider an implementation of XOR gate used in logic. XOR gate outputs 1 when both the inputs are 1 or both the inputs are 0. It outputs 0 when one input is 0 and one input is 1.

Application of state pattern for XOR gate:

Consider two states, ZERO and ONE.

If the system is initially in state ZERO:

If the input message is 0, system goes into state ONE.

If the input message is 1, state does not change.

If system is initially in state ONE:

If the input message is 0, system goes into state ZERO.

If the input message is 1, state of the system does not change. We can use state pattern to implement this example with two states state ZERO and state ONE. There are two input signals input_zero and input_one.

  • [4]A bank account can change from an open account to a closed account and back to an open account again. The behavior of the two types of accounts is different.
  • A chocolate vending machine can have states like waiting for coins, has coin, sold and sold out. There are actions performed for transitioning among the states like insert coins, dispense chocolate and return coin.
  • [5]A simplified version of the Post Office Protocol used to download e-mail from a mail server. The code can be in states QUIT, HAVE_USER_NAME, START and AUTHORIZED and actions for transitioning between these states can be USER username, PASS password, LIST <message number>, RETR <message number> and QUIT.

Structure


[6] The diagram above shows the class diagram for State Pattern Implementation. There is a Context class which communicates with the outside world. This class maintains the state of the corresponding object. It can have a number of internal states. The Context class is also called as Wrapper class. An interface State defines a common interface for all the concrete states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time.

State transition logic can be defined either in the wrapper class or in each individual state subclass. If it is included in wrapper class, structure becomes static, i.e., we can’t dynamically add new states to the structure. On the other hand, if it is included in each individual class, it results in increased coupling.

A Real Life Example

Scenario

Consider an example of a bulb which works in three modes, namely, Off, dim and normal. Initially, the bulb is in off state. When we turn the switch, it glows and goes into dim state. If we turn the switch again, it goes into normal state. It again goes into off state on turning the switch.

A Possible Inefficient Java Implementation

package patterns;
class LightStateContext {
   private int currentState;
   public LightStateContext() {
      currentState = 0;
   }
   public void turnSwitch(){
       if (currentState == 0){
          currentState = 1;
          System.out.println("change to dim state.");
       } else if (currentState == 1){
          currentState = 2;
          System.out.println("change to normal state.");
       } else if (currentState == 2){
          currentState = 0;
          System.out.println("change to off state.");
       } 
    }
}
public class InefficientCodeDemo{
   public static void main(String[] args) {
      LightStateContext context = new LightStateContext();
         while (true) {
            context.turnSwitch();
         }
   }
}

The method turnSwitch acts as finite state machine for this scenario. It contains the conditional logic for state transitions. A lot of 'if else' statements make the code unnecessarily complex. Also, to add another state for the bulb, we need to change the original LightStateContext class which makes this code inefficient and difficult to extend.

A Better Solution

A better solution can be provided using the state pattern. We can clearly identify the three states of the bulb, off, dim and normal. We can also formulate the logic for finite state machine.

  1. If light is in 'off' state and we turn the switch, resulting state is 'dim'.
  2. If light is in 'dim' state and we turn the switch, resulting state is 'normal'.
  3. If light is in 'normal' state and we turn the switch, resulting state is 'off'.

The finite state machine for the states can be seen below.

The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.

Steps to Implement State Pattern

  1. Identify the states and define values for each state (typically constants)
  2. Create an instance variable that holds the current state.
  3. Identify all the actions that can occur in the system and find out all the actions that can cause state transition.
  4. Create a class that acts as the state machine.
  5. For each state, create a class which contains system behavior for that state and implements State.

Java Implementation Using State Pattern

  1. Class LightStateContext acts as finite state machine for this example. This class contains the state variable 'currentState'. It includes the action 'turnSwitch' and a method 'setCurrentState' to set the state of the bulb when turnSwitch is called.
  2. State interface contains turnSwitch method which is called by the context class.
  3. A class is created for each individual state. These classes implement the State interface and turnSwitch method of State interface is defined by these classes.
package patterns;
class LightStateContext {
   private State currentState;
   public LightStateContext() {
      currentState = new OffState();
   }
   public State getCurrentState() {
      return currentState;
   }
   public void setCurrentState(State currentState) {
      this.currentState = currentState;
   }
   public void turnSwitch(){
      currentState.turnSwitch(this);
   }
}
interface State{
    void turnSwitch(LightStateContext context);	
}
class OffState implements State{
   @override
   public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new DimState());
      System.out.println("change to dim state.");
   }
}
class DimState implements State{
   @Override
   public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new NormalState());
      System.out.println("change to normal state.");
   }
}
class NormalState implements State{
@Override
   public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new OffState());
      System.out.println("change to off state.");
   }
}
public class StatePatternDemo {
   public static void main(String[] args) {
   LightStateContext context = new LightStateContext();
   while (true) 
      context.turnSwitch();
   }
}

The output for the above program is:

change to dim state.
change to normal state.
change to bright state.
change to off state.

and so on till the program terminates.

Ruby Implementation Using State Pattern

The State Pattern implementation using Ruby for the same bulb scenario mentioned above is seen below.

  1. Module State contains methods to initialize states, delete states, check whether a state exists and a method for transitions of the states.
  2. This module is included by Context class which acts as finite state machine for this example.
  3. Input signal for each state is the 'turnswitch' method. For each state, turnswitch method is defined in the Context class.
  4. When the turnswitch method for any context is called, turnswitch method for the current state is executed.
  5. Context class also includes a method reset which resets the current context into Off state.

[7]

module State
   class StateInitError < Exception; end
   class StateSetError < Exception; end
   def with_key(key, ex, &b)
      if (@s_states.has_key?(key))
         yield b
      else
         raise(ex, "No such state `#{key}'", caller)
      end
   end
   def accept_states(*states)
      @s_states  = {}
      @s_initial = @s_current = states[0]
      states.each { |s| @s_states[s] = nil }
   end
   def reject_states(*states)
      states.each { |s|
         @s_states.delete(s)
         if (@s_current == s)
            if (@s_initial == s)
               @s_current = nil
            else
               @s_current = @s_initial
            end
         end
      }
   end
   def transition_to(s)
      with_key(s, StateSetError) {
         if (@s_states[s])
            @s_states[s].call
         end
         @s_current = s
      }
   end
   def state(s=nil, &b)
      return @s_current if (s.nil?)
      with_key(s, StateInitError) {
         if (block_given?)
            @s_states[s] = b
         if (@s_initial == s)
            transition_to(s)
         end
         else
          transition_to(s)
         end
      }
   end
end
########
class Context
   include(State)
   def initialize()
      accept_states(:offstate, :dimstate, :normalstate)
      state(:offstate) {
         def turnswitch
            puts("starting the bulb")
            transition_to(:dimstate)
         end
      }
      state(:dimstate) {
         def turnswitch
            puts("turning to normal")
            transition_to(:normalstate)
         end
      }
      state(:normalstate) {
         def turnswitch
            puts("switch off the bulb")
            transition_to(:offstate)
         end
      }
   end
   def reset()
      puts("resetting outside a state")
      transition_to(:offstate)
   end
end
c = Context.new
c.turnswitch # start the bulb state:dimstate
c.turnswitch    # change to state:normalstate
c.turnswitch    # change to state:offstate
c.reset      # reseting outside a state changes to state:offstate
p c.state    # print current state

The output for the above is as seen below.

starting the bulb
turning to normal
switch off the bulb
resetting outside a state
offstate

Another example in Java using the state pattern

Consider an implementation of XOR gate used in logic. XOR gate outputs 1 when both the inputs are 1 or both the inputs are 0. It outputs 0 when one input is 0 and one input is 1.

Application of the state pattern for XOR gate is as follows.

Consider two states, ZERO and ONE.

1. If the system is initially in state ZERO:
-If the input message is 0, state does not change.
-If the input message is 1, system goes into state ONE.

2. If system is initially in state ONE:
-If the input message is 0, state does not change.
-If the input message is 1, system goes into state ZERO.

The finite state machine below describes the state transitions on performing the various actions.

The code for implementing this scenario using the state pattern is seen below.

package patterns;
class XOR{
   private State current_state;
   public XOR(){
      current_state = new Zero();
   }
   public void set_state(State s){
      current_state = s;
   }
   public void input_zero(){
      current_state.input_zero(this);
   }
   public void input_one(){
      current_state.input_one(this);
   }
}
//State base interface.
interface State{
   void input_zero(XOR wrapper);
   void input_one(XOR wrapper);
}
//class for state ZERO
class Zero implements State {
   @Override
   public void input_zero(XOR wrapper){
      System.out.println("New state : ZERO");
      wrapper.set_state(new Zero());
   }
   @Override
   public void input_one(XOR wrapper) {
      System.out.println("New state : ONE");
      wrapper.set_state(new One());
   }
}
//class for state ONE
class One implements State{
   @Override
   public void input_zero(XOR wrapper){
      System.out.println("New state : ONE");
      wrapper.set_state(new One());
   }
   @Override
   public void input_one(XOR wrapper){
      System.out.println("New state : ZERO");
      wrapper.set_state(new Zero());
   }
}
public class XorStateDemo {
   public static void main(String args[]){
      XOR gate = new XOR();
      int num = 1;  //get input from user
      if (num == 0)
         gate.input_zero();
      if (num == 1)
         gate.input_one();
   }
}

The output for the above program is, New state : One

Thus from the initial state zero on the action input_one, the current state changes to one.

Advantages

[8] Advantages of the state pattern can be summarized as:

  1. One object for one state.
  2. Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.
  3. Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.
  4. By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.
  5. If the state pattern is implemented correctly, the code becomes easy to extend.

Let us assume we are asked to show that when the bulb is in the normal state and we turn the switch the bulb glows bright. To incorporate this kind of change we need to just do the following:

1. Add a new BrightState that implements the State interface

class BrightState implements State{
 @Override
   public void turnSwitch(LightStateContext context) {
      context.setCurrentState(new OffState());
       System.out.println("change to off state.");
   }
}

2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState

context.setCurrentState(new BrightState());

The finite state machine that depicts this requirement by adding a new state is as seen below.

Limitations

[9]

  1. Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.
  2. Becomes too heavy when Finite State Machine is not that complex.

Strategy Pattern Vs State Pattern

[10]A Strategy pattern is another behavioral software design pattern which separates the behavioral algorithms from the object. Each algorithm is encapsulated in a different class. Depending upon the properties of the current object, decision of invoking an algorithm is taken at runtime.

The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.

  1. The patterns differ in their intent. In a strategy pattern, the client specifies the strategy object that the client is composed with. There is a strategy object that is most appropriate for the context object. For example, Two sorting algorithms (Merge Sort and Quick sort) are implemented and the client can select either of the algorithms for sorting a list. In a state pattern, we have a set of behaviors encapsulated in state objects, at any time the context is delegating to one of those states. The current state changes with every action to reflect the internal state of the context. The client usually knows very little about the state objects.
  2. In a strategy pattern, once a decision is made to invoke a particular algorithm, it is not possible to change it. Whereas in state pattern, transition between states occurs at runtime.
  3. In state pattern, decision of which state to invoke depends only on one variable.
  4. We can say that state pattern is a type of strategy pattern where each state represents a different behavioral algorithm for the object in context.

A class that performs validation on incoming data may use a strategy pattern to select a validation algorithm based on the type of data, the source of the data, user choice, and/or other discriminating factors. These factors are not known for each case until run-time, and may require radically different validation to be performed. A state pattern can be used for implementing a drawing program. The program has many tools like pointer, fill shape which at any point in time can act as one of several tools. Instead of switching between multiple objects, the code maintains an internal state representing the tool currently in use.

Conclusion

The State pattern can be used to replace to replace many ifs or switch statements. Thus inconsistent states can be avoided since state changes occur using just the one state object. Code becomes more understandable and maintainable. There are a few disadvantages of using the state pattern but the advantages outweigh the disadvantages.

References

  1. Behavioural Patterns
  2. Behavioural Patterns Description
  3. State Pattern
  4. State Pattern Example-Bank Account
  5. State Pattern Example-Post Office Protocol
  6. State Pattern Class Diagram
  7. Ruby Implementation of Bulb Example
  8. Advantages of State Pattern
  9. Limitations of State Pattern
  10. Strategy Pattern Description

Further References

  1. Freeman,Freeman,Bates,Sierra,Robson.Head First Design Patterns,2004, O'Reilly
  2. http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html