201802272223->深入浅出设计模式:c#状态模式
2018-02-27 22:24
489 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _020状态模式
{
public interface LightState
{
void Press(Light light);
}
public class TurnOff : LightState
{
public void Press(Light light)
{
light.State = new TurnOn();
Console.WriteLine("turn on the light");
}
}
public class TurnOn : LightState
{
public void Press(Light light)
{
light.State = new TurnOff();
Console.WriteLine("turn off the light");
}
}
public class Light
{
public LightState State;
public Light()
{
this.State = new TurnOff();
}
public void Press()
{
State.Press(this);
}
}
internal class Program
{
private static void Main(string[] args)
{
Light light = new Light();
light.Press();
light.Press();
light.Press();
/*
* 状态模式
*
* 利用接口实现不同的逻辑,根据逻辑实现需求
*
* 与策略模式相似
*
* 但策略模式偏向外部实现逻辑,状态模式比较偏向内部实现逻辑,
*
* 外部只需要调用接口则可以改变对象内部的状态,实现不同的逻辑
*
*/
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _020状态模式
{
public interface LightState
{
void Press(Light light);
}
public class TurnOff : LightState
{
public void Press(Light light)
{
light.State = new TurnOn();
Console.WriteLine("turn on the light");
}
}
public class TurnOn : LightState
{
public void Press(Light light)
{
light.State = new TurnOff();
Console.WriteLine("turn off the light");
}
}
public class Light
{
public LightState State;
public Light()
{
this.State = new TurnOff();
}
public void Press()
{
State.Press(this);
}
}
internal class Program
{
private static void Main(string[] args)
{
Light light = new Light();
light.Press();
light.Press();
light.Press();
/*
* 状态模式
*
* 利用接口实现不同的逻辑,根据逻辑实现需求
*
* 与策略模式相似
*
* 但策略模式偏向外部实现逻辑,状态模式比较偏向内部实现逻辑,
*
* 外部只需要调用接口则可以改变对象内部的状态,实现不同的逻辑
*
*/
Console.ReadKey();
}
}
}
相关文章推荐
- 201802282138->深入浅出设计模式:c#访问者模式
- 201802170025->深入浅出设计模式:c#组合模式
- 201802272130->深入浅出设计模式:c#观察者模式
- 201802141508->深入浅出设计模式:c#创建者模式
- 201802262211->深入浅出设计模式:c#备忘录模式
- 201802121524->深入浅出设计模式:c#简单工厂模式
- 201802132228->深入浅出设计模式:c#抽象工厂模式
- 201802191355->深入浅出设计模式:c#解析器模式
- 201802191355->深入浅出设计模式:c#迭代器模式
- 201802151200->深入浅出设计模式:c#适配器模式
- 201802151313->深入浅出设计模式:c#桥模式
- 201802181505->深入浅出设计模式:c#装饰者模式
- 201802181721->深入浅出设计模式:c#享元模式
- 201802141601->深入浅出设计模式:c#原型模式
- 201802191230->深入浅出设计模式:c#代理模式
- 201802140000->深入浅出设计模式:c#高并发下单例模式
- 201802181537->深入浅出设计模式:c#外观模式
- 201802272238->深入浅出设计模式:c#模板模式
- (Boolan)C++设计模式 <十> ——状态模式(State)和备忘录(Memento)
- (C#)设计模式之状态模式