Design Patterns
  • Introduction
  • Proto-Pattern
  • Anti-pattern
  • OO Design Principles
  • Classification
  • Creational Design Patterns
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Prototype
  • Structural design patterns
    • Adapter
    • Bridge
    • Composite
    • Decorator
    • Facade
    • Flyweight
    • Proxy
  • Behavioural Design Pattern
    • Chain of Responsibility
    • Command
    • Interpreter
    • Iterator
    • Mediator
    • Memento
    • Observer
    • State
    • Strategy
    • Template Method
    • Visitor
  • Concurrency Design Pattern
  • Architectural Design Pattern
  • Modern Desing Patterns
Powered by GitBook
On this page

Was this helpful?

  1. Behavioural Design Pattern

State

Alter an object's behavior when its state changes.

  • The State pattern provides state-specific logic to a limited set of objects in which each object represents a particular state.

  • In State pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.

EX:
class AlertStateContext { 
    private currentState;  
    public AlertStateContext()  
    { 
        currentState = new Vibration(); 
    }  
    public setState(state)  
    { 
        currentState = state; 
    }  
    public alert()  
    { 
        currentState.alert(this); 
    } 
} 
  
class Vibration {
    public alert(AlertStateContext ctx)  
    { 
         System.out.println("vibration..."); 
    }  
} 
  
class Silent {
    public void alert(AlertStateContext ctx)  
    { 
        System.out.println("silent..."); 
    }  
} 
  
function run() {
    AlertStateContext stateContext = new AlertStateContext(); 
    stateContext.alert(); // vibration...
    stateContext.alert(); // vibration...
    stateContext.setState(new Silent()); 
    stateContext.alert(); // silent...
    stateContext.alert(); // silent...
    stateContext.alert(); // silent...
}

run();
PreviousObserverNextStrategy

Last updated 5 years ago

Was this helpful?