Condition (design sample)

from Wikipedia, the free encyclopedia

The condition ( English state ) is a design pattern in the field of software development , which in the category of behavior patterns (English patterns design behavioral ) belongs. The state pattern is used to encapsulate different, state-dependent behaviors of an object.

The state pattern is one of the so-called "GoF" patterns, i. H. it is one of the design patterns in the book . Elements of reusable object-oriented software listed design patterns ("GoF" stands for "Gang of Four" or "Gang of Four" after the four authors of this book published in 1994). The state pattern is also known as "Objects for States" ( objects for states ).

use

Basically, the behavior of an object depends on its state. The usual implementation is intended to switchavoid encoding the states of an object and the behavior dependent on them in a large statement (based on enumerated constants). Each instance of the switchstatement should be implemented in its own class, so that the state of the object itself is an object that is independent of other objects.

problem

State machine

Different states, the possible transitions between these states and the behavior that depends on them must be defined for an object. This is shown here in the form of a finite automaton . The black circle points to the start state and the black circle with the white border points to the end state. The directed edges (arrows) between the states Closed, Openand Deleteddefine the state change.

State diagram

Hierarchical state machine

A single state of an object can in turn be divided into a number of different states. The state Opencan be divided into read and write , for example . They form a compound state Open. Closedas well as Deletedviewed independently of the composite state Open. These states can be arranged in a hierarchy. Open, Closedand Deletedare on the first level. The second level contains Read and Write , which Openare assigned to the status .

solution

Simple states

The state-dependent behavior of the object is outsourced to separate classes, with a separate class being introduced for each possible state, which defines the behavior of the object in this state. A common abstraction of these classes is defined so that the context can handle the separate status classes uniformly.

In the case of a state transition, the context exchanges the state object used by it.

Class diagram

actors

Three actors play a role in the design pattern of the state. The context defines the client-side interface and manages the separate state classes. In addition, it exchanges these when there is a state transition.

The state defines a uniform interface for all state objects and, if necessary, implements a standard behavior. For example, the execution of any behavior can be blocked in the abstract state. The behavior can be carried out in this case only if it from the concrete state by overriding the appropriate method enabled was.

The concrete state in turn implements the behavior associated with the state of the context object.

variants

  • For the actor state , an interface can be defined instead of an abstract class.
  • If several contexts can use the same status objects (if the status can be defined by their respective classes and not by instances or property values ​​can be swapped out into the context [e.g. the file name]), storage space can be saved.

Advantages and disadvantages

One advantage of the system is that complex and difficult-to-read conditional statements can be avoided. In addition, new states and new behaviors can easily be added. The maintainability is increased and state objects can be reused.

On the other hand, the benefits of very simple stateful behavior may not justify the sometimes considerable implementation effort. If the object can assume a large number of states in which only very few actions are allowed, each state must nevertheless contain code for each action of the other states in order to implement the interface correctly, even if only one exception handling takes place in each of them . In a large conditional statement, however, the exception handling can be combined in a common "otherwise" branch.

Examples

In principle, any state-dependent behavior can be mapped using this design pattern . For example, it is used for the administration of sessions or of input and output streams, for status-related control elements of a graphical user interface or for parking machines.

Java

Here is an example of the state behavior pattern:

interface Statelike {

    void writeName(final StateContext STATE_CONTEXT, final String NAME);
}

class StateA implements Statelike {

    @Override
    public void writeName(final StateContext STATE_CONTEXT, final String NAME) {
        System.out.println(NAME.toLowerCase());
        STATE_CONTEXT.setState(new StateB());
    }
}

class StateB implements Statelike {
    /** State counter */
    private int count = 0;

    @Override
    public void writeName(final StateContext STATE_CONTEXT, final String NAME) {
        System.out.println(NAME.toUpperCase());
        // Change state after StateB's writeName() gets invoked twice
        if(++count > 1) {
            STATE_CONTEXT.setState(new StateA());
        }
    }
}

The context class has a state variable which it StateAinstantiates here as in an initial state. In its methods it uses the corresponding methods of the state object.

public class StateContext {
    private Statelike myState;

    public StateContext() {
        setState(new StateA());
    }

    public void setState(final Statelike NEW_STATE) {
        myState = NEW_STATE;
    }

    public void writeName(final String NAME) {
        myState.writeName(this, NAME);
    }
}

The test below is also intended to illustrate its use:

public class TestClientState {
    public static void main(String[] args) {
        final StateContext SC = new StateContext();

        SC.writeName("Montag");
        SC.writeName("Dienstag");
        SC.writeName("Mittwoch");
        SC.writeName("Donnerstag");
        SC.writeName("Freitag");
        SC.writeName("Samstag");
        SC.writeName("Sonntag");
    }
}

According to the code above, the output of the main()method is TestClientState:

montag
DIENSTAG
MITTWOCH
donnerstag
FREITAG
SAMSTAG
sonntag

Web links

Wikibooks: State  - Implementation of the state in different languages

Individual evidence

  1. Erich Gamma , Richard Helm , Ralph Johnson , John Vlissides : Design pattern. Elements of reusable object-oriented software . 5th edition. Addison-Wesley , 1996, ISBN 3-8273-1862-9 , pp. 398 (English: Design Patterns. Elements of Reusable Object-Oriented Software. ).