某一对象由于有不同的状态,而产生不同的行为。
using System;using System.Collections;using System.Collections.Generic;using System.Linq;namespace ConsoleApplication1{ class Program { public interface IDoorState { void Switch(Door door); } public class DoorOn : IDoorState { public void Switch(Door door) { Console.WriteLine("door off"); door.DoorState = new DoorOff(); } } public class DoorOff : IDoorState { public void Switch(Door door) { Console.WriteLine("door on"); door.DoorState = new DoorOn(); } } public class Door { public IDoorState DoorState { get; set; } public Door() { DoorState = new DoorOff(); } public void Switch() { DoorState.Switch(this); } } static void Main(string[] args) { Door door = new Door(); door.Switch(); door.Switch(); door.Switch(); } }}