Sunday, January 5, 2014

State Design Pattern Java Example

SHARE & COMMENT :
1
State design pattern falls under the category of Behavioural patterns. Assume that we have an object and its behavior is largely dependent on the state of its internal variables.
State pattern allows, object to behave in different ways depends on the internal state. State pattern is defined in the book Gang of four is,
Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.
Consider the following example,
Person.java
1package tips.pattern.state;
2public class Person {
3    private String name;
4    private String character;
5 
6    public Person(String name, String character) {
7        this.name = name;
8        this.character = character;
9    }
10 
11    public void giveMeMoney() {
12        if (character.equals("GoodCharacter")) {
13            System.out.println("Yes, take all my money");
14        else if (character.equals("BadCharacter")) {
15            System.out.println("No, I dont have anything with me");
16        else if (character.equals("OtherCharacter")) {
17            System.out.println("I will give the money tmrw");
18        }
19    }
20}
We have modeled a Person object passing his name and a string representing his character, which may be a Good Character or Bad Character or some Other Character. If someone comes to him and asks for money by calling thePerson.giveMeMoney() method, his behavior is entirely dependant on his character. Technically, his behavior is tightly coupled with the internal variable character.
state-design-patternImage Credit )
The above design has one great dis-advantage. Suppose we want to add further characters that represent some other different behavior of a Person, then we end up in adding if-else clauses, which certainly is not very good from a design perspective because of changes being done in the existing code.
So, how to provide support for different characteristic behaviors for a person without making code changes? Here comes theState pattern which just do that. The State pattern mandates to model behavior as interfaces rather than representing them as Strings or some other types. For example, since character is the changing behavior for a Person, let us encapsulate it by having something like the following,
Character.java
1package tips.pattern.state;
2 
3public interface Character {
4    public void giveMeMoney();
5}
See, we have modeled a person’s Character as an interface. Now, let us see the implementation for different characteristic feature of a person, say GoodCharacter and BadCharacter.
GoodCharacter.java
1package tips.pattern.state;
2 
3public class GoodCharacter implements Character {
4    @Override
5    public void giveMeMoney() {
6        System.out.println("Yes, take all my money");
7    }
8}
BadCharacter.java
1package tips.pattern.state;
2 
3public class BadCharacter implements Character {
4    @Override
5    public void giveMeMoney() {
6        System.out.println("No, I dont have anything with me");
7    }
8}
Now, let us see the new Person class which accepts character in the form of an interface rather than as a String. Given below is the code snippet for the same.
Person2.java
1package tips.pattern.state;
2 
3public class Person2 {
4    private String name;
5    private Character character;
6 
7    public Person2(String name, Character character) {
8        this.name = name;
9        this.character = character;
10    }
11 
12    public void giveMeMoney() {
13        character.giveMeMoney();
14    }
15 
16    public static void main(String[] args) {
17        Person2 object = new Person2("John"new GoodCharacter());
18        object.giveMeMoney();
19        object = new Person2("John"new BadCharacter());
20        object.giveMeMoney();
21    }
22}
Since now the character is represented as an interface, there wont be any more code changes if there is a need to add new characteristic behavior. All we need to do is to define the new character class implementing the Character interface.
The following two tabs change content below.

6 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Anna said...

Great and Useful Article.

Online Java Training

Online Java Course

Java EE course

Java Course in Chennai

Java Training in Chennai

Java Training Institutes in Chennai

Java Interview Questions

Java Interview Questions

raybanoutlet001 said...

kobe byrant shoes
mlb jerseys
michael kors outlet store
cheap true religion jeans
oakley sunglasses
nike huaraches
links of london
cheap mlb jerseys
adidas nmd
michael kors handbags clearance
cheap jordan shoes
kobe shoes
michael kors handbags
yeezy boost
nike huarache
michael kors handbags sale
michael kors handbags
nike kobe sneakers
nike huarache
air jordan retro
tiffany and co jewellery
ralph lauren online
http://www.uggoutlet.uk