Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

State

Context delegates to current State object; behavior shifts as state swaps.

C#

// State interface
interface IState
{
	string Handle(Context c);
}

// Concrete state: ON
class On : IState
{
	public string Handle(Context c)
	{
		c.State = new Off();
		return "on->off"; // transitioned to Off
	}
}

// Concrete state: OFF
class Off : IState
{
	public string Handle(Context c)
	{
		c.State = new On();
		return "off->on"; // transitioned to On
	}
}

// Context delegates behavior to current state object
class Context
{
	public IState State { get; set; } = new Off();
	public string Press() => State.Handle(this);
}

// Usage / Demo
var ctx = new Context();
string first = ctx.Press(); // off->on
string second = ctx.Press(); // on->off
next