creativity in code.

creativity is that spark of electricity before an explosion.
it allows us, in a single instance to explore all possibilities without hesitation.

Programming - State Behavioral Design Pattern


Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.and
The classes and/or objects participating in this example are:


  • Context
    and
    • 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


// State pattern -- Structural example

using
System;

namespace
DoFactory.GangOfFour.State.Structural
{

// MainApp test application

class MainApp
{
static void Main()
{
// Setup context in a state
Context c = new Context(new ConcreteStateA());

// Issue requests, which toggles state
c.Request();
c.Request();
c.Request();
c.Request();

// Wait for user
Console.Read();
}
}

// "State"

abstract class State
{
public abstract void Handle(Context context);
}

// "ConcreteStateA"

class ConcreteStateA : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateB();
}
}

// "ConcreteStateB"

class ConcreteStateB : State
{
public override void Handle(Context context)
{
context.State = new ConcreteStateA();
}
}

// "Context"

class Context
{
private State state;

// Constructor
public Context(State state)
{
this.State = state;
}

// Property
public State State
{
get{ return state; }
set
{
state = value;
Console.WriteLine("State: " +
state.GetType().Name);
}
}

public void Request()
{
state.Handle(this);
}
}
}
Output expected:


State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA
State: ConcreteStateB
State: ConcreteStateA



Other pages of interest:
[+] Programming - Prototype Design Pattern
[+] Programming - Proxy Structural Design Pattern
[+] Programming - Iterator Behavioral Design Pattern
[+] Programming - Prototype Design Pattern
[+] Programming - Proxy Structural Design Pattern
[+] Programming - Iterator Behavioral Design Pattern
[+] Programming - Prototype Design Pattern
[+] Programming - Proxy Structural Design Pattern
[+] Programming - Iterator Behavioral Design Pattern
[+] Programming - Prototype Design Pattern
[+] Programming - Proxy Structural Design Pattern
[+] Programming - Iterator Behavioral Design Pattern
[+] Request Quote
[+] Programming - Prototype Design Pattern
[+] Programming - Proxy Structural Design Pattern


Comments(0)

add comment Add Comment

Add your comment

Email address:
Your name:
Do you want your email to be visible?: