State Design Pattern .NET Code Sample

Posted on Microsoft .NET Support Team See other posts from Microsoft .NET Support Team
Published on Sun, 25 Sep 2011 20:03:00 +0000 Indexed on 2011/11/11 18:15 UTC
Read the original article Hit count: 281

Filed under:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
static void Main(string[] args)
{
Person p1 = new Person("P1");
Person p2 = new Person("P2");
p1.EatFood();
p2.EatFood();
p1.Vomit();
p2.Vomit();
}
}



interface StomachState
{
void Eat(Person p);
void Vomit(Person p);
}

class StomachFull : StomachState
{
public void Eat(Person p)
{
Console.WriteLine("Can't eat more.");
}

public void Vomit(Person p)
{
Console.WriteLine("I've just Vomited.");
p.StomachState = new StomachEmpty();
}
}

class StomachEmpty : StomachState
{
public void Eat(Person p)
{
Console.WriteLine("I've just had food.");
p.StomachState = new StomachFull();
}

public void Vomit(Person p)
{
Console.WriteLine("Nothing to Vomit.");
}
}

class Person
{
private StomachState stomachState;
private String personName;
public Person(String personName)
{
this.personName = personName;
StomachState = new StomachEmpty();
}

public StomachState StomachState
{
get
{
return stomachState;
}
set
{
stomachState = value;
Console.WriteLine(personName + " Stomach State Changed to " + StomachState.GetType().Name);
Console.WriteLine("***********************************************\n");
}
}

public Person(StomachState StomachState)
{
this.StomachState = StomachState;
}

public void EatFood()
{
StomachState.Eat(this);
}

public void Vomit()
{
StomachState.Vomit(this);
}
}

© Microsoft .NET Support Team or respective owner