<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Pshegde</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Pshegde"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Pshegde"/>
	<updated>2026-05-08T14:46:30Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_E805_kkn&amp;diff=82243</id>
		<title>CSC/ECE 517 Fall 2013/oss E805 kkn</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_E805_kkn&amp;diff=82243"/>
		<updated>2013-10-31T04:29:15Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Problem Inference and Motivation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
Expertiza&amp;lt;ref name=&amp;quot;expertiza&amp;gt;''Expertiza'' Retrieved from http://wikis.lib.ncsu.edu/index.php/Expertiza&amp;lt;/ref&amp;gt; is a web application where students can submit and peer-review learning objects (articles, code, web sites, etc). It is used in select courses at NC State and by professors at several other colleges and universities. The Expertiza project is software to create reusable learning objects through peer review. It also supports team projects, and the submission of almost any document type, including URLs and wiki pages. It is an open source project developed on Ruby on Rails platform. More information on Expertiza can be found [https://github.com/expertiza/expertiza here]. The source code can be forked and cloned for making modifications. &lt;br /&gt;
&lt;br /&gt;
This wiki provides an insight into our contributions to the Open Source Software project Expertiza with main focus on the UI changes for reporting scores. Reporting score functionality is handled by controllers/grades_controller.rb and rendered by views/grades/_view_my_score.html.erb. Improved User Interface using JQuery is our contribution to Expertiza. This new elegant UI uses tabs instead of tables which makes it look elegant and renders faster. Subtle code and design challenges, changes and the motivation to implement this design have been explained further.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
The view_my_scores html.erb page is being slow-rendered. The page displays all the scores in a tabular form with reviews, metareviews, author feedback below each other. Everything is merged into one big html page, and this makes the view rendering a slow process. Also, the user interface is not aesthetically pleasing. The challenge here is to make appropriate changes to the views so that the rendering time becomes less as well as to improve the over-all look and feel of the score report page.&lt;br /&gt;
&lt;br /&gt;
Classes: grades_controller.rb (241 lines), and probably other classes used by this &lt;br /&gt;
What it does: This class is responsible for displaying grades to students (via view_my_scores) and &lt;br /&gt;
instructors (via the view method). &lt;br /&gt;
&lt;br /&gt;
===What needs to be done:=== &lt;br /&gt;
* This code is very slow, due to many factors. Two of the most prominent are the fact that separate &lt;br /&gt;
db queries are used for each rubric that has been filled out by anyone associated with the &lt;br /&gt;
assignment; these queries are made sequentially while the HTML page is being written; and the &lt;br /&gt;
fact that HTML for the whole page is generated, largely by controller methods, before anything is &lt;br /&gt;
displayed. This project deals with the second of these concerns. &lt;br /&gt;
&lt;br /&gt;
* Move as much html as possible from the controllers into the views. Logic should be handled by &lt;br /&gt;
the controllers/models, and the views should simply access those variables set by the controller. &lt;br /&gt;
HTML should be in html.erb files, not written by controller files. &lt;br /&gt;
&lt;br /&gt;
* Rather than write HTML for displaying all of the reviews on a single page, only the summary &lt;br /&gt;
information for each student and team should be written. This should work more like the Review &lt;br /&gt;
Report that an instructor can view (see review_mapping_controller.rb). This shows each review &lt;br /&gt;
in a popup when the user clicks on a particular review. You don’t need to use a popup; the &lt;br /&gt;
review could be populated on the current page when a user clicks on “Show reviews”.&lt;br /&gt;
&lt;br /&gt;
===Problem Inference and Motivation===&lt;br /&gt;
*Currently the view_my_scores html.erb page displays all the scores in a tabular form with reviews,metareviews,author feedback below each other. Everything is merged into one big html page, and thus makes the view rendering a slow process. Also it’s a very bad user interface design. &lt;br /&gt;
[[File:scr1.png]]&lt;br /&gt;
&lt;br /&gt;
*When a user clicks on show reviews/metareviews,etc the reviews gets rendered below each other which is too taxing for a  student to scroll all the way down to read a particular review.&lt;br /&gt;
[[File:scr2.png]]&lt;br /&gt;
&lt;br /&gt;
*This bad User Interface design along with very slow view rendering process motivated us to design an elegant interface which is user friendly and well as fast. This prompted us to use JQuery tabs.&lt;br /&gt;
&lt;br /&gt;
== Design ==&lt;br /&gt;
We have implemented partial rendering for the HTML page. The tabs are created using JQuery. The advantage of using JQuery is that it enables a sleeker and cleaner interface on pages without requiring the page to be loaded all at once. The new view page is visually aesthetic as it separates the scoring tabs as well as the review tabs and each review is rendered only when the tab for that review is clicked on. Thereby this approach overcomes the previous issue of the entire page being rendered at once.&lt;br /&gt;
&lt;br /&gt;
==Initial User Interface to view scores==&lt;br /&gt;
Previously,the view_my_scores html.erb page displayed all the scores in a tabular form with reviews, metareviews, author feedback below each other. Everything is merged into one big html page, and thus makes the view rendering a slow process. Also it’s a very bad user interface &lt;br /&gt;
design.&lt;br /&gt;
&lt;br /&gt;
When a user clicks on show reviews/metareviews,etc the reviews gets rendered below each other&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Modified User Interface to view scores and reviews in tabs==&lt;br /&gt;
&lt;br /&gt;
The new user interface separates the code into various tabs for reporting the scores and also a tab format for displaying reviews.&lt;br /&gt;
==Code Changes==&lt;br /&gt;
 Score for &amp;lt;%= @assignment.name%&amp;gt;&lt;br /&gt;
 &amp;lt;TABLE class=&amp;quot;grades&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;%= render :partial =&amp;gt; 'grades/participant_title', :locals =&amp;gt; {:prefix =&amp;gt; nil} %&amp;gt;&lt;br /&gt;
   &amp;lt;%= render :partial =&amp;gt; 'grades/participant', :locals =&amp;gt; {:prefix =&amp;gt; 'user',  :team =&amp;gt; false, :pscore=&amp;gt;@participant.get_scores(@questions)} %&amp;gt;&lt;br /&gt;
 &amp;lt;/TABLE&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We have now refactored the code such that the _participant.html.erb partial includes other partials.Each of these partials corresponds to a tab in the view-my-scores page.&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;div id=&amp;quot;tabs&amp;quot;&amp;gt;&lt;br /&gt;
                              &amp;lt;ul&amp;gt;&lt;br /&gt;
        		&amp;lt;li id=&amp;quot;tab1&amp;quot;&amp;gt;&amp;lt;a href=&amp;quot;#tabs-11&amp;quot;&amp;gt;Submitted Work&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
       			 &amp;lt;li id=&amp;quot;tab2&amp;quot;&amp;gt;&amp;lt;a href=&amp;quot;#tabs-12&amp;quot;&amp;gt;Reviewing&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
      			  &amp;lt;li id=&amp;quot;tab3&amp;quot;&amp;gt;&amp;lt;a href=&amp;quot;#tabs-13&amp;quot;&amp;gt;Author Feedback&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
      			  &amp;lt;li id=&amp;quot;tab4&amp;quot;&amp;gt;&amp;lt;a href=&amp;quot;#tabs-14&amp;quot;&amp;gt;TeamMate Review&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;&lt;br /&gt;
     		 &amp;lt;/ul&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;tabs-11&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;p&amp;gt;&amp;lt;%= render :partial =&amp;gt; 'grades/submittedwork', :locals =&amp;gt; {:prefix =&amp;gt; 'user',  :team =&amp;gt; false, :pscore =&amp;gt; @participant.get_scores(@questions)} %&amp;gt; &amp;lt;/p&amp;gt;&lt;br /&gt;
      &amp;lt;/div&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;tabs-12&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;%= render :partial =&amp;gt; 'grades/meta', :locals =&amp;gt; {:prefix =&amp;gt; 'user',  :team =&amp;gt; false, :pscore =&amp;gt; @participant.get_scores(@questions)} %&amp;gt;&lt;br /&gt;
      &amp;lt;/div&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;tabs-13&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;%= render :partial =&amp;gt; 'grades/author',:locals =&amp;gt; {:prefix =&amp;gt; 'user',  :team =&amp;gt; false, :pscore =&amp;gt; @participant.get_scores(@questions)} %&amp;gt;&lt;br /&gt;
      &amp;lt;/div&amp;gt;&lt;br /&gt;
      &amp;lt;div id=&amp;quot;tabs-14&amp;quot;&amp;gt;&lt;br /&gt;
        &amp;lt;%= render :partial =&amp;gt; 'grades/teammate',:locals =&amp;gt; {:prefix =&amp;gt; 'user',  :team =&amp;gt; false, :pscore =&amp;gt; @participant.get_scores(@questions)} %&amp;gt;&lt;br /&gt;
      &amp;lt;/div&amp;gt;&lt;br /&gt;
    &amp;lt;/div&amp;gt;&lt;br /&gt;
    &amp;lt;script&amp;gt;&lt;br /&gt;
        jQuery(document).ready(function () {&lt;br /&gt;
            jQuery(&amp;quot;#tabs&amp;quot;).tabs();&lt;br /&gt;
        });&lt;br /&gt;
    &amp;lt;/script&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Testing the new User Interface==&lt;br /&gt;
Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers. By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring. Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.&lt;br /&gt;
&lt;br /&gt;
===Testing with Cucumber===&lt;br /&gt;
Cucumber&amp;lt;ref name=&amp;quot;cucumber&amp;quot;&amp;gt;''Cucumber'' Retrieved from https://github.com/cucumber/cucumber-rails&amp;lt;/ref&amp;gt; is a high-level testing framework. It is used commonly to perform various integration tests. We used Cucumber to test our new tabbed user interface. Cucumber is used extensively in Expertiza. It constitutes some of the main test cases. All cucumber test scenarios are under Features.&lt;br /&gt;
&lt;br /&gt;
===View My Score Test===&lt;br /&gt;
To test the improved user interface, we had to modify already existing test scenario with the following modifications.&lt;br /&gt;
&lt;br /&gt;
 Feature: View scores for an assignment&lt;br /&gt;
  In order to view resulting scores&lt;br /&gt;
  As a student&lt;br /&gt;
 &lt;br /&gt;
 @wip&lt;br /&gt;
 Scenario: View my submitted work scores&lt;br /&gt;
  Given I am logged in as a student&lt;br /&gt;
    And I move to the &amp;quot;Assignments&amp;quot; page&lt;br /&gt;
    And I click the &amp;quot;test_Metareview&amp;quot; link&lt;br /&gt;
    And I click the &amp;quot;Your scores&amp;quot; link&lt;br /&gt;
    And I have a work review with score of &amp;quot;85&amp;quot;&lt;br /&gt;
    And I have a work review with score of &amp;quot;66&amp;quot;&lt;br /&gt;
    And I have a work review with score of &amp;quot;99&amp;quot;&lt;br /&gt;
  When I click the &amp;quot;show reviews&amp;quot; link&lt;br /&gt;
  Then I should see the three reviews for my submitted work with corresponding scores&lt;br /&gt;
 &lt;br /&gt;
 @wip&lt;br /&gt;
 Scenario: View my author feedback scores&lt;br /&gt;
  Given I am logged in as a student&lt;br /&gt;
    And I move to the &amp;quot;Assignments&amp;quot; page&lt;br /&gt;
    And I click the &amp;quot;test_Metareview&amp;quot; link&lt;br /&gt;
    And I click the &amp;quot;Your scores&amp;quot; link&lt;br /&gt;
    And I have a feedback review with score of &amp;quot;93&amp;quot;&lt;br /&gt;
  When I click the &amp;quot;show author feedbacks&amp;quot; link&lt;br /&gt;
  Then I should see the author feedback review with corresponding score&lt;br /&gt;
 &lt;br /&gt;
 @wip&lt;br /&gt;
 Scenario: View my teammate review scores&lt;br /&gt;
  Given I am logged in as a student&lt;br /&gt;
    And I move to the &amp;quot;Assignments&amp;quot; page&lt;br /&gt;
    And I click the &amp;quot;test_Metareview&amp;quot; link&lt;br /&gt;
    And I click the &amp;quot;Your scores&amp;quot; link&lt;br /&gt;
    And I have a teammate review with score of &amp;quot;100&amp;quot;&lt;br /&gt;
    And I have a teammate review with score of &amp;quot;100&amp;quot;&lt;br /&gt;
  When I click the &amp;quot;show teammate reviews&amp;quot; link&lt;br /&gt;
  Then I should see the two teammate reviews with corresponding scores&lt;br /&gt;
&lt;br /&gt;
==Future Work==&lt;br /&gt;
In the current implementation of the model separate DB queries are made sequentially while the HTML page is being written. This increases the loading time of the page. Hence to make views faster, models and methods should be re-factored too.&lt;br /&gt;
 &lt;br /&gt;
* Merge this project with [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2013/oss_E804_spb e804] which deals with an efficient way to query DB models to return scores,without UI changes. This will make the review rendering process fast.&lt;br /&gt;
* View_my_Score method in the controller saves the questionnaire in a hashmap. It needs re-factoring to make it optimal.&lt;br /&gt;
* Total score tab needs to be displayed either to the right or left or remaining tabs.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Scr1.png&amp;diff=82241</id>
		<title>File:Scr1.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Scr1.png&amp;diff=82241"/>
		<updated>2013-10-31T04:25:54Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: New file&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;New file&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69403</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69403"/>
		<updated>2012-11-03T20:14:16Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Structure */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
The State Pattern implementation using Ruby for the same bulb scenario mentioned above is seen below.&lt;br /&gt;
&lt;br /&gt;
#Module State contains methods to initialize states, delete states, check whether a state exists and a method for transitions of the states.&lt;br /&gt;
#This module is included by Context class which acts as finite state machine for this example.&lt;br /&gt;
#Input signal for each state is the 'turnswitch' method. For each state, turnswitch method is defined in the Context class.&lt;br /&gt;
#When the turnswitch method for any context is called, turnswitch method for the current state is executed.&lt;br /&gt;
#Context class also includes a method reset which resets the current context into Off state.&lt;br /&gt;
&lt;br /&gt;
[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html]&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is as seen below.&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html Ruby Implementation of Bulb Example]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69375</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69375"/>
		<updated>2012-11-01T00:09:15Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
The State Pattern implementation using Ruby for the same bulb scenario mentioned above is seen below.&lt;br /&gt;
&lt;br /&gt;
#Module State contains methods to initialize states, delete states, check whether a state exists and a method for transitions of the states.&lt;br /&gt;
#This module is included by Context class which acts as finite state machine for this example.&lt;br /&gt;
#Input signal for each state is the 'turnswitch' method. For each state, turnswitch method is defined in the Context class.&lt;br /&gt;
#When the turnswitch method for any context is called, turnswitch method for the current state is executed.&lt;br /&gt;
#Context class also includes a method reset which resets the current context into Off state.&lt;br /&gt;
&lt;br /&gt;
[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html]&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is as seen below.&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://rightfootin.blogspot.com/2006/08/implementing-state-pattern-in-ruby.html Ruby Implementation of Bulb Example]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69366</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69366"/>
		<updated>2012-10-31T23:18:56Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is as seen below.&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69365</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69365"/>
		<updated>2012-10-31T23:18:37Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69364</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69364"/>
		<updated>2012-10-31T23:18:23Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
: offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69363</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69363"/>
		<updated>2012-10-31T23:18:02Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;ignore&amp;gt;:offstate&amp;lt;/ignore&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69361</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69361"/>
		<updated>2012-10-31T23:12:56Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
\:offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69360</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69360"/>
		<updated>2012-10-31T23:12:34Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # start the bulb state:dimstate&lt;br /&gt;
 c.turnswitch    # change to state:normalstate&lt;br /&gt;
 c.turnswitch    # change to state:offstate&lt;br /&gt;
 c.reset      # reseting outside a state changes to state:offstate&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
turning to normal&amp;lt;br&amp;gt;&lt;br /&gt;
switch off the bulb&amp;lt;br&amp;gt;&lt;br /&gt;
resetting outside a state&amp;lt;br&amp;gt;&lt;br /&gt;
:offstate&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69359</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69359"/>
		<updated>2012-10-31T23:10:41Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* A Possible Java Implementation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Inefficient Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # not connected yet&lt;br /&gt;
 c.turnswitch    # connected&lt;br /&gt;
 c.turnswitch    # already connected&lt;br /&gt;
 c.reset      # reseting outside a state&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_correct.png&amp;diff=69358</id>
		<title>File:Fsm correct.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_correct.png&amp;diff=69358"/>
		<updated>2012-10-31T23:09:12Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69357</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69357"/>
		<updated>2012-10-31T23:09:00Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # not connected yet&lt;br /&gt;
 c.turnswitch    # connected&lt;br /&gt;
 c.turnswitch    # already connected&lt;br /&gt;
 c.reset      # reseting outside a state&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ONE&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;New state : ZERO&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
New state : One &lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69356</id>
		<title>File:Fsm xor correct.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69356"/>
		<updated>2012-10-31T23:07:26Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: uploaded a new version of &amp;amp;quot;File:Fsm xor correct.png&amp;amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69355</id>
		<title>File:Fsm xor correct.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69355"/>
		<updated>2012-10-31T23:06:48Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: uploaded a new version of &amp;amp;quot;File:Fsm xor correct.png&amp;amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69353</id>
		<title>File:Fsm xor correct.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_correct.png&amp;diff=69353"/>
		<updated>2012-10-31T23:01:33Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69352</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69352"/>
		<updated>2012-10-31T23:01:19Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # not connected yet&lt;br /&gt;
 c.turnswitch    # connected&lt;br /&gt;
 c.turnswitch    # already connected&lt;br /&gt;
 c.reset      # reseting outside a state&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_correct.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;current state is zero&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;changing the state to one&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;changing the state to zero&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;current state is one&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
changing the state to one&lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69351</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69351"/>
		<updated>2012-10-31T22:53:18Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
 module State&lt;br /&gt;
    class StateInitError &amp;lt; Exception; end&lt;br /&gt;
    class StateSetError &amp;lt; Exception; end&lt;br /&gt;
    def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
       if (@s_states.has_key?(key))&lt;br /&gt;
          yield b&lt;br /&gt;
       else&lt;br /&gt;
          raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
       end&lt;br /&gt;
    end&lt;br /&gt;
    def accept_states(*states)&lt;br /&gt;
       @s_states  = {}&lt;br /&gt;
       @s_initial = @s_current = states[0]&lt;br /&gt;
       states.each { |s| @s_states[s] = nil }&lt;br /&gt;
    end&lt;br /&gt;
    def reject_states(*states)&lt;br /&gt;
       states.each { |s|&lt;br /&gt;
          @s_states.delete(s)&lt;br /&gt;
          if (@s_current == s)&lt;br /&gt;
             if (@s_initial == s)&lt;br /&gt;
                @s_current = nil&lt;br /&gt;
             else&lt;br /&gt;
                @s_current = @s_initial&lt;br /&gt;
             end&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def transition_to(s)&lt;br /&gt;
       with_key(s, StateSetError) {&lt;br /&gt;
          if (@s_states[s])&lt;br /&gt;
             @s_states[s].call&lt;br /&gt;
          end&lt;br /&gt;
          @s_current = s&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def state(s=nil, &amp;amp;b)&lt;br /&gt;
       return @s_current if (s.nil?)&lt;br /&gt;
       with_key(s, StateInitError) {&lt;br /&gt;
          if (block_given?)&lt;br /&gt;
             @s_states[s] = b&lt;br /&gt;
          if (@s_initial == s)&lt;br /&gt;
             transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
          else&lt;br /&gt;
           transition_to(s)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 ########&lt;br /&gt;
 class Context&lt;br /&gt;
    include(State)&lt;br /&gt;
    def initialize()&lt;br /&gt;
       accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
       state(:offstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:dimstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:dimstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
             transition_to(:normalstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
       state(:normalstate) {&lt;br /&gt;
          def turnswitch&lt;br /&gt;
             puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
             transition_to(:offstate)&lt;br /&gt;
          end&lt;br /&gt;
       }&lt;br /&gt;
    end&lt;br /&gt;
    def reset()&lt;br /&gt;
       puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
       transition_to(:offstate)&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
 c = Context.new&lt;br /&gt;
 c.turnswitch # not connected yet&lt;br /&gt;
 c.turnswitch    # connected&lt;br /&gt;
 c.turnswitch    # already connected&lt;br /&gt;
 c.reset      # reseting outside a state&lt;br /&gt;
 p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;current state is zero&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       System.out.println(&amp;quot;changing the state to one&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;changing the state to zero&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       System.out.println(&amp;quot;current state is one&amp;quot;);&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 1;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is,&lt;br /&gt;
changing the state to one&lt;br /&gt;
&lt;br /&gt;
Thus from the initial state zero on the action input_one, the current state changes to one.&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69349</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69349"/>
		<updated>2012-10-31T22:46:25Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Java Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to normal state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to bright state.&amp;lt;br&amp;gt;&lt;br /&gt;
change to off state.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69348</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69348"/>
		<updated>2012-10-31T22:46:06Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Java Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The output for the above program is:&lt;br /&gt;
&lt;br /&gt;
change to dim state.&lt;br /&gt;
change to normal state.&lt;br /&gt;
change to bright state.&lt;br /&gt;
change to off state.&lt;br /&gt;
&lt;br /&gt;
and so on till the program terminates.&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69347</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69347"/>
		<updated>2012-10-31T22:43:39Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Ruby Implementation Using State Pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
The output for the above is&lt;br /&gt;
&lt;br /&gt;
starting the bulb&lt;br /&gt;
turning to normal&lt;br /&gt;
switch off the bulb&lt;br /&gt;
resetting outside a state&lt;br /&gt;
:offstate&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69346</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69346"/>
		<updated>2012-10-31T22:39:21Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation Using State Pattern==&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69345</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69345"/>
		<updated>2012-10-31T22:38:32Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
==Ruby Implementation using the state pattern==&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69344</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69344"/>
		<updated>2012-10-31T22:37:58Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Ruby Implementation using the state pattern=&lt;br /&gt;
&lt;br /&gt;
module State&lt;br /&gt;
  class StateInitError &amp;lt; Exception; end&lt;br /&gt;
  class StateSetError &amp;lt; Exception; end&lt;br /&gt;
  def with_key(key, ex, &amp;amp;b)&lt;br /&gt;
    if (@s_states.has_key?(key))&lt;br /&gt;
      yield b&lt;br /&gt;
    else&lt;br /&gt;
      raise(ex, &amp;quot;No such state `#{key}'&amp;quot;, caller)&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  def accept_states(*states)&lt;br /&gt;
    @s_states  = {}&lt;br /&gt;
    @s_initial = @s_current = states[0]&lt;br /&gt;
    states.each { |s| @s_states[s] = nil }&lt;br /&gt;
  end&lt;br /&gt;
  def reject_states(*states)&lt;br /&gt;
    states.each { |s|&lt;br /&gt;
      @s_states.delete(s)&lt;br /&gt;
      if (@s_current == s)&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          @s_current = nil&lt;br /&gt;
        else&lt;br /&gt;
          @s_current = @s_initial&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def transition_to(s)&lt;br /&gt;
    with_key(s, StateSetError) {&lt;br /&gt;
      if (@s_states[s])&lt;br /&gt;
        @s_states[s].call&lt;br /&gt;
      end&lt;br /&gt;
      @s_current = s&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
  def state(s=nil, &amp;amp;b)&lt;br /&gt;
    return @s_current if (s.nil?)&lt;br /&gt;
    with_key(s, StateInitError) {&lt;br /&gt;
      if (block_given?)&lt;br /&gt;
        @s_states[s] = b&lt;br /&gt;
        if (@s_initial == s)&lt;br /&gt;
          transition_to(s)&lt;br /&gt;
        end&lt;br /&gt;
      else&lt;br /&gt;
        transition_to(s)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
########&lt;br /&gt;
&lt;br /&gt;
class Context&lt;br /&gt;
  include(State)&lt;br /&gt;
  def initialize()&lt;br /&gt;
    accept_states(:offstate, :dimstate, :normalstate)&lt;br /&gt;
    state(:offstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;starting the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:dimstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:dimstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;turning to normal&amp;quot;)&lt;br /&gt;
        transition_to(:normalstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    state(:normalstate) {&lt;br /&gt;
      def turnswitch&lt;br /&gt;
        puts(&amp;quot;switch off the bulb&amp;quot;)&lt;br /&gt;
        transition_to(:offstate)&lt;br /&gt;
      end&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
  end&lt;br /&gt;
  def reset()&lt;br /&gt;
    puts(&amp;quot;resetting outside a state&amp;quot;)&lt;br /&gt;
    transition_to(:offstate)&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
c = Context.new&lt;br /&gt;
c.turnswitch # not connected yet&lt;br /&gt;
c.turnswitch    # connected&lt;br /&gt;
c.turnswitch    # already connected&lt;br /&gt;
&lt;br /&gt;
c.reset      # reseting outside a state&lt;br /&gt;
p c.state    # print current state&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69343</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69343"/>
		<updated>2012-10-31T22:10:19Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69342</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69342"/>
		<updated>2012-10-31T22:10:11Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69341</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69341"/>
		<updated>2012-10-31T22:10:01Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &amp;lt;br&amp;gt;&lt;br /&gt;
1. If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
2. If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69340</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69340"/>
		<updated>2012-10-31T22:09:32Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
1. If the system is initially in state ZERO:&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&lt;br /&gt;
2. If system is initially in state ONE:&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69339</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69339"/>
		<updated>2012-10-31T22:09:13Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
#If the system is initially in state ZERO:&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state does not change.&lt;br /&gt;
#If system is initially in state ONE:&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&amp;lt;br&amp;gt;&lt;br /&gt;
-If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69338</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69338"/>
		<updated>2012-10-31T22:08:48Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
#If the system is initially in state ZERO:&lt;br /&gt;
-If the input message is 0, system goes into state ONE.&lt;br /&gt;
-If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
#If system is initially in state ONE:&lt;br /&gt;
-If the input message is 0, system goes into state ZERO.&lt;br /&gt;
-If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The code for implementing this scenario using the state pattern is seen below.&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_resize.png&amp;diff=69337</id>
		<title>File:Fsm xor resize.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor_resize.png&amp;diff=69337"/>
		<updated>2012-10-31T22:07:25Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69336</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69336"/>
		<updated>2012-10-31T22:07:13Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor_resize.png]]&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor.png&amp;diff=69335</id>
		<title>File:Fsm xor.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_xor.png&amp;diff=69335"/>
		<updated>2012-10-31T22:05:59Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69334</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69334"/>
		<updated>2012-10-31T22:05:37Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
The finite state machine below describes the state transitions on performing the various actions.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_xor.png]]&lt;br /&gt;
&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class XOR{&lt;br /&gt;
    private State current_state;&lt;br /&gt;
    public XOR(){&lt;br /&gt;
       current_state = new Zero();&lt;br /&gt;
    }&lt;br /&gt;
    public void set_state(State s){&lt;br /&gt;
       current_state = s;&lt;br /&gt;
    }&lt;br /&gt;
    public void input_zero(){&lt;br /&gt;
       current_state.input_zero(this);&lt;br /&gt;
    }&lt;br /&gt;
    public void input_one(){&lt;br /&gt;
       current_state.input_one(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //State base interface.&lt;br /&gt;
 interface State{&lt;br /&gt;
    void input_zero(XOR wrapper);&lt;br /&gt;
    void input_one(XOR wrapper);&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ZERO&lt;br /&gt;
 class Zero implements State {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper) {&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 //class for state ONE&lt;br /&gt;
 class One implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_zero(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new Zero());&lt;br /&gt;
    }&lt;br /&gt;
    @Override&lt;br /&gt;
    public void input_one(XOR wrapper){&lt;br /&gt;
       wrapper.set_state(new One());&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class XorStateDemo {&lt;br /&gt;
    public static void main(String args[]){&lt;br /&gt;
       XOR gate = new XOR();&lt;br /&gt;
       int num = 0;  //get input from user&lt;br /&gt;
       if (num == 0)&lt;br /&gt;
          gate.input_zero();&lt;br /&gt;
       if (num == 1)&lt;br /&gt;
          gate.input_one();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#[http://sourcemaking.com/behavioral_patterns Behavioural Patterns]&lt;br /&gt;
#[http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm Behavioural Patterns Description]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Bank Account]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf State Pattern Example-Post Office Protocol]&lt;br /&gt;
#[http://sourcemaking.com/design_patterns/state State Pattern Class Diagram]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Advantages of State Pattern]&lt;br /&gt;
#[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1 Limitations of State Pattern]&lt;br /&gt;
#[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf Strategy Pattern Description]&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69316</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69316"/>
		<updated>2012-10-31T05:45:09Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;Work in progress&amp;gt;&lt;br /&gt;
    package patterns;&lt;br /&gt;
    class XOR{&lt;br /&gt;
         private State current_state;&lt;br /&gt;
	 public XOR(){&lt;br /&gt;
             current_state = new Zero();&lt;br /&gt;
	 }&lt;br /&gt;
	&lt;br /&gt;
	 public void set_state(State s){&lt;br /&gt;
	     current_state = s;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
         public void input_zero(){&lt;br /&gt;
	     current_state.input_zero(this);&lt;br /&gt;
	 }&lt;br /&gt;
&lt;br /&gt;
	 public void input_one(){&lt;br /&gt;
	     current_state.input_one(this);&lt;br /&gt;
	 }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    //State base interface.&lt;br /&gt;
    interface State{&lt;br /&gt;
	void input_zero(XOR wrapper);&lt;br /&gt;
	void input_one(XOR wrapper);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
//class for state ZERO&lt;br /&gt;
class Zero implements State&lt;br /&gt;
{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper) {&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ONE&lt;br /&gt;
class One implements State{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class XorStateDemo&lt;br /&gt;
{&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		XOR gate = new XOR();&lt;br /&gt;
		int num = 0;  //get input from user&lt;br /&gt;
		if (num == 0)&lt;br /&gt;
			gate.input_zero();&lt;br /&gt;
		if (num == 1)&lt;br /&gt;
			gate.input_one();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69315</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69315"/>
		<updated>2012-10-31T05:44:34Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
    package patterns;&lt;br /&gt;
    class XOR{&lt;br /&gt;
         private State current_state;&lt;br /&gt;
	 public XOR(){&lt;br /&gt;
             current_state = new Zero();&lt;br /&gt;
	 }&lt;br /&gt;
	&lt;br /&gt;
	 public void set_state(State s){&lt;br /&gt;
	     current_state = s;&lt;br /&gt;
	 }&lt;br /&gt;
	 &lt;br /&gt;
         public void input_zero(){&lt;br /&gt;
	     current_state.input_zero(this);&lt;br /&gt;
	 }&lt;br /&gt;
&lt;br /&gt;
	 public void input_one(){&lt;br /&gt;
	     current_state.input_one(this);&lt;br /&gt;
	 }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    //State base interface.&lt;br /&gt;
    interface State{&lt;br /&gt;
	void input_zero(XOR wrapper);&lt;br /&gt;
	void input_one(XOR wrapper);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
//class for state ZERO&lt;br /&gt;
class Zero implements State&lt;br /&gt;
{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper) {&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ONE&lt;br /&gt;
class One implements State{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class XorStateDemo&lt;br /&gt;
{&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		XOR gate = new XOR();&lt;br /&gt;
		int num = 0;  //get input from user&lt;br /&gt;
		if (num == 0)&lt;br /&gt;
			gate.input_zero();&lt;br /&gt;
		if (num == 1)&lt;br /&gt;
			gate.input_one();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69314</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69314"/>
		<updated>2012-10-31T05:43:44Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
    package patterns;&lt;br /&gt;
    class XOR{&lt;br /&gt;
         private State current_state;&lt;br /&gt;
	public XOR(){&lt;br /&gt;
		current_state = new Zero();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void set_state(State s){&lt;br /&gt;
		current_state = s;&lt;br /&gt;
	}&lt;br /&gt;
	public void input_zero(){&lt;br /&gt;
		current_state.input_zero(this);&lt;br /&gt;
	}&lt;br /&gt;
	public void input_one(){&lt;br /&gt;
		current_state.input_one(this);&lt;br /&gt;
	}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    //State base interface.&lt;br /&gt;
    interface State{&lt;br /&gt;
	void input_zero(XOR wrapper);&lt;br /&gt;
	void input_one(XOR wrapper);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
//class for state ZERO&lt;br /&gt;
class Zero implements State&lt;br /&gt;
{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper) {&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ONE&lt;br /&gt;
class One implements State{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class XorStateDemo&lt;br /&gt;
{&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		XOR gate = new XOR();&lt;br /&gt;
		int num = 0;  //get input from user&lt;br /&gt;
		if (num == 0)&lt;br /&gt;
			gate.input_zero();&lt;br /&gt;
		if (num == 1)&lt;br /&gt;
			gate.input_one();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69313</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69313"/>
		<updated>2012-10-31T05:43:11Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
    package patterns;&lt;br /&gt;
    class XOR{&lt;br /&gt;
	private State current_state;&lt;br /&gt;
	public XOR(){&lt;br /&gt;
		current_state = new Zero();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void set_state(State s){&lt;br /&gt;
		current_state = s;&lt;br /&gt;
	}&lt;br /&gt;
	public void input_zero(){&lt;br /&gt;
		current_state.input_zero(this);&lt;br /&gt;
	}&lt;br /&gt;
	public void input_one(){&lt;br /&gt;
		current_state.input_one(this);&lt;br /&gt;
	}&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    //State base interface.&lt;br /&gt;
    interface State{&lt;br /&gt;
	void input_zero(XOR wrapper);&lt;br /&gt;
	void input_one(XOR wrapper);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
//class for state ZERO&lt;br /&gt;
class Zero implements State&lt;br /&gt;
{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper) {&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ONE&lt;br /&gt;
class One implements State{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class XorStateDemo&lt;br /&gt;
{&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		XOR gate = new XOR();&lt;br /&gt;
		int num = 0;  //get input from user&lt;br /&gt;
		if (num == 0)&lt;br /&gt;
			gate.input_zero();&lt;br /&gt;
		if (num == 1)&lt;br /&gt;
			gate.input_one();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69312</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69312"/>
		<updated>2012-10-31T05:42:00Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Another example in Java using the state pattern */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Application of the state pattern for XOR gate is as follows.&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
If the system is initially in state ZERO:&lt;br /&gt;
if the input message is 0, system goes into state ONE.&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&lt;br /&gt;
if the input message is 0, system goes into state ZERO.&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
    package patterns;&lt;br /&gt;
&lt;br /&gt;
class XOR&lt;br /&gt;
{&lt;br /&gt;
	private State current_state;&lt;br /&gt;
	public XOR(){&lt;br /&gt;
		current_state = new Zero();&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	public void set_state(State s){&lt;br /&gt;
		current_state = s;&lt;br /&gt;
	}&lt;br /&gt;
	public void input_zero(){&lt;br /&gt;
		current_state.input_zero(this);&lt;br /&gt;
	}&lt;br /&gt;
	public void input_one(){&lt;br /&gt;
		current_state.input_one(this);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//State base interface.&lt;br /&gt;
interface State&lt;br /&gt;
{&lt;br /&gt;
	void input_zero(XOR wrapper);&lt;br /&gt;
	void input_one(XOR wrapper);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ZERO&lt;br /&gt;
class Zero implements State&lt;br /&gt;
{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper) {&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
//class for state ONE&lt;br /&gt;
class One implements State{&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_zero(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new Zero());&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void input_one(XOR wrapper){&lt;br /&gt;
		wrapper.set_state(new One());&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class XorStateDemo&lt;br /&gt;
{&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
		XOR gate = new XOR();&lt;br /&gt;
		int num = 0;  //get input from user&lt;br /&gt;
		if (num == 0)&lt;br /&gt;
			gate.input_zero();&lt;br /&gt;
		if (num == 1)&lt;br /&gt;
			gate.input_one();&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69311</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69311"/>
		<updated>2012-10-31T05:27:27Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Another example in Java using the state pattern=&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69310</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69310"/>
		<updated>2012-10-31T05:17:26Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=Conclusion=&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_resize.png&amp;diff=69309</id>
		<title>File:Class resize.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Class_resize.png&amp;diff=69309"/>
		<updated>2012-10-31T05:09:21Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69308</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69308"/>
		<updated>2012-10-31T05:09:08Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* A Better Solution */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:class_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69307</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69307"/>
		<updated>2012-10-31T05:04:22Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:classdiagram.jpeg]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:After_resize.png&amp;diff=69306</id>
		<title>File:After resize.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:After_resize.png&amp;diff=69306"/>
		<updated>2012-10-31T05:02:03Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69305</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69305"/>
		<updated>2012-10-31T05:01:52Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:classdiagram.jpeg]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[[File:fsm_newstate.png|thumb|FSM Adding new state]]&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:after_resize.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69304</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69304"/>
		<updated>2012-10-31T04:53:37Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:classdiagram.jpeg]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[[File:fsm_newstate.png|thumb|FSM Adding new state]]&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
The finite state machine that depicts this requirement by adding a new state is as seen below.&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_newstate.png]]&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69303</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69303"/>
		<updated>2012-10-31T04:52:00Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* A Better Solution */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
The class diagram for the way in which this scenario can be implemented using the state pattern is as seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:classdiagram.jpeg]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[[File:fsm_newstate.png|thumb|FSM Adding new state]]&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69302</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w21 ap</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w21_ap&amp;diff=69302"/>
		<updated>2012-10-31T04:50:32Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: /* A Better Solution */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;[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.&lt;br /&gt;
The design patterns are divided into creational patterns, structural patterns and behavioral patterns.&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Behavioral Patterns=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
=State Pattern=&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
[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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
Static conditional statements are replaced by a finite state machine which decides the transition flow of the object.&lt;br /&gt;
&lt;br /&gt;
=Examples=&lt;br /&gt;
We should use the State pattern in the following scenario:&lt;br /&gt;
*When an object's behavior depends on its state, and it must change its behavior at run-time depending on that state&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A few scenarios in which the state pattern can be used:&lt;br /&gt;
*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.&lt;br /&gt;
Application of state pattern for XOR gate:&lt;br /&gt;
&lt;br /&gt;
Consider two states, ZERO and ONE. &lt;br /&gt;
&lt;br /&gt;
If the system is initially in state ZERO:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ONE.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state does not change.&lt;br /&gt;
&lt;br /&gt;
If system is initially in state ONE:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If the input message is 0, system goes into state ZERO.&lt;br /&gt;
&lt;br /&gt;
If the input message is 1, state of the system does not change.&lt;br /&gt;
&lt;br /&gt;
*[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.&lt;br /&gt;
&lt;br /&gt;
*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.&lt;br /&gt;
&lt;br /&gt;
*[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 &amp;lt;message number&amp;gt;, RETR &amp;lt;message number&amp;gt; and QUIT.&lt;br /&gt;
&lt;br /&gt;
=Structure=&lt;br /&gt;
[[File:genclass.png]]&lt;br /&gt;
&amp;lt;br&amp;gt;&lt;br /&gt;
[http://sourcemaking.com/design_patterns/state]&lt;br /&gt;
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 concreate states. The states all implement the same interface; thus they are interchangeable. Our code can be in one of these states at a time. &lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=A Real Life Example=&lt;br /&gt;
==Scenario==&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Possible Java Implementation==&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private int currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = 0;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
        if (currentState == 0){&lt;br /&gt;
           currentState = 1;&lt;br /&gt;
           System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 1){&lt;br /&gt;
           currentState = 2;&lt;br /&gt;
           System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
        } else if (currentState == 2){&lt;br /&gt;
           currentState = 0;&lt;br /&gt;
           System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
        } &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 public class InefficientCodeDemo{&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
       LightStateContext context = new LightStateContext();&lt;br /&gt;
          while (true) {&lt;br /&gt;
             context.turnSwitch();&lt;br /&gt;
          }&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==A Better Solution==&lt;br /&gt;
[[File:classdiagram.jpeg|thumb|Class Diagram]]&lt;br /&gt;
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.&lt;br /&gt;
#If light is in 'off' state and we turn the switch, resulting state is 'dim'.&lt;br /&gt;
#If light is in 'dim' state and we turn the switch, resulting state is 'normal'.&lt;br /&gt;
#If light is in 'normal' state and we turn the switch, resulting state is 'off'.&lt;br /&gt;
&lt;br /&gt;
The finite state machine for the states can be seen below.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:fsm_resize.png]]&lt;br /&gt;
&lt;br /&gt;
==Steps to Implement State Pattern==&lt;br /&gt;
#Identify the states and define values for each state (typically constants) &lt;br /&gt;
#Create an instance variable that holds the current state.&lt;br /&gt;
#Identify all the actions that can occur in the system and find out all the actions that can cause state transition.&lt;br /&gt;
#Create a class that acts as the state machine.&lt;br /&gt;
#For each state, create a class which contains system behavior for that state and implements State.&lt;br /&gt;
&lt;br /&gt;
==Java Implementation Using State Pattern==&lt;br /&gt;
#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. &lt;br /&gt;
# State interface contains turnSwitch method which is called by the context class.&lt;br /&gt;
# 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.&lt;br /&gt;
 package patterns;&lt;br /&gt;
 class LightStateContext {&lt;br /&gt;
    private State currentState;&lt;br /&gt;
    public LightStateContext() {&lt;br /&gt;
       currentState = new OffState();&lt;br /&gt;
    }&lt;br /&gt;
    public State getCurrentState() {&lt;br /&gt;
       return currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void setCurrentState(State currentState) {&lt;br /&gt;
       this.currentState = currentState;&lt;br /&gt;
    }&lt;br /&gt;
    public void turnSwitch(){&lt;br /&gt;
       currentState.turnSwitch(this);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 interface State{&lt;br /&gt;
     void turnSwitch(LightStateContext context);	&lt;br /&gt;
 }&lt;br /&gt;
 class OffState implements State{&lt;br /&gt;
    @override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new DimState());&lt;br /&gt;
       System.out.println(&amp;quot;change to dim state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class DimState implements State{&lt;br /&gt;
    @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new NormalState());&lt;br /&gt;
       System.out.println(&amp;quot;change to normal state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 class NormalState implements State{&lt;br /&gt;
 @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
       System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
 public class StatePatternDemo {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
    LightStateContext context = new LightStateContext();&lt;br /&gt;
    while (true) &lt;br /&gt;
       context.turnSwitch();&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[[File:fsm_newstate.png|thumb|FSM Adding new state]]&lt;br /&gt;
[http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf]&lt;br /&gt;
Advantages of the state pattern can be summarized as:&lt;br /&gt;
#One object for one state. &lt;br /&gt;
#Allows state transition logic to be be incorporated into a state object rather than in a monolithic if or switch statement.&lt;br /&gt;
#Helps avoid inconsistent states since state changes occur using just the one state object and not several objects or attributes.&lt;br /&gt;
#By using objects we can make the states explicit and reduce the effort needed to understand and maintain the code.&lt;br /&gt;
#If the state pattern is implemented correctly, the code becomes easy to extend.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
1. Add a new BrightState that implements the State interface&lt;br /&gt;
&lt;br /&gt;
 class BrightState implements State{&lt;br /&gt;
  @Override&lt;br /&gt;
    public void turnSwitch(LightStateContext context) {&lt;br /&gt;
       context.setCurrentState(new OffState());&lt;br /&gt;
        System.out.println(&amp;quot;change to off state.&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
2. In the previous state's (NormalState) turnSwitch method set the current state to BrightState&lt;br /&gt;
&lt;br /&gt;
 context.setCurrentState(new BrightState());&lt;br /&gt;
&lt;br /&gt;
=Limitations= &lt;br /&gt;
[https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1]&lt;br /&gt;
#Too many objects are created. This is a price that we need to pay for better flexibility and maintainability.&lt;br /&gt;
#Becomes too heavy when Finite State Machine is not that complex.&lt;br /&gt;
&lt;br /&gt;
=Strategy Pattern Vs State Pattern=&lt;br /&gt;
[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.&lt;br /&gt;
&lt;br /&gt;
The class diagrams of these two patterns are similar in structure. However, there are a few differences between these patterns.&lt;br /&gt;
#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.&lt;br /&gt;
#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.&lt;br /&gt;
#In state pattern, decision of which state to invoke depends only on one variable. &lt;br /&gt;
#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.&lt;br /&gt;
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.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
#http://sourcemaking.com/behavioral_patterns&lt;br /&gt;
#http://www.allapplabs.com/java_design_patterns/behavioral_patterns.htm&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#http://sourcemaking.com/design_patterns/state&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
#https://docs.google.com/a/ncsu.edu/viewer?a=v&amp;amp;q=cache:UGImuHnhO8MJ:www.cs.toronto.edu/~arnold/407/06s/lectures/studentPresentations/stateStrategy/state_strat_pres.ppt+disadvantages+of+strategy+pattern&amp;amp;hl=en&amp;amp;gl=us&amp;amp;pid=bl&amp;amp;srcid=ADGEEShbX8h_8wQ7PkIoXMKwXjPgISI7dduhY-HrO8fUV8lntQw0RYYWQ-eG_hLAxTT3pjUj5j5Dj8F7-baC3D-C6Znv_YTujBdB_E6-WkZ9KMe2jWXGtZgeRtMcwEJtpqN8JNOC9itc&amp;amp;sig=AHIEtbSP_rpR12IcGL1KyQAhi0PGeUQqrQ&amp;amp;pli=1&lt;br /&gt;
#http://userpages.umbc.edu/~tarr/dp/lectures/StateStrategy.pdf&lt;br /&gt;
&lt;br /&gt;
=Further References=&lt;br /&gt;
#Freeman,Freeman,Bates,Sierra,Robson.''Head First Design Patterns'',2004, O'Reilly&lt;br /&gt;
#http://www.freetechbooks.com/the-design-patterns-java-companion-t126.html&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_resize.png&amp;diff=69301</id>
		<title>File:Fsm resize.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Fsm_resize.png&amp;diff=69301"/>
		<updated>2012-10-31T04:49:43Z</updated>

		<summary type="html">&lt;p&gt;Pshegde: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Pshegde</name></author>
	</entry>
</feed>