Core Java

State Pattern

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Participants

  • Context: defines the interface of interest to clients Maintains an instance of a ConcreteState subclass that defines the current state.
  • State: defines an interface for encapsulating the behavior associated with a particular state of the Context.
  • Concrete State: each subclass implements a behavior associated with a state of Context

Code

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class Main {
    public static void main(String[] args) {
        Context c = new Context(new ConcreteStateA());
        c.request();
        c.request();
        c.request();
        c.request();
    }
}
public interface State {
    void handle(Context context);
}
public class ConcreteStateA implements State {
    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateB());
    }
}
public class ConcreteStateB implements State {
    @Override
    public void handle(Context context) {
        context.setState(new ConcreteStateA());
    }
}
public class Context {
    private State state;
    public Context(State state) {
        setState(state);
    }
    public State getState() {
        return state;
    }
    public void setState(State state) {
        this.state = state;
        System.out.println("State: " + state.getClass().getSimpleName());
    }
    public void request() {
        state.handle(this);
    }
}

Output

1
2
3
4
5
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA

eidherjulian61 / design-patterns

Published on Java Code Geeks with permission by Eidher Julian, partner at our JCG program. See the original article here: State Pattern

Opinions expressed by Java Code Geeks contributors are their own.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Eidher Julian

Eidher Julian is a Systems Engineer and Software Engineering Specialist with 13+ years of experience as a Java developer. He is an Oracle Certified Associate and SOA Certified Architect.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button