状态模式

using System;

namespace MyApp

{

class Program

{

static void Main()

{

Account myAccount = new Account();

myAccount.Level = 10;

myAccount.ShowCurrentState();

Console.WriteLine();

myAccount.Level = 30;

myAccount.ShowCurrentState();

Console.WriteLine();

myAccount.Level = 45;

myAccount.ShowCurrentState();

Console.WriteLine();

myAccount.Level = 67;

myAccount.ShowCurrentState();

Console.WriteLine();

myAccount.Level = 9;

myAccount.ShowCurrentState();

Console.ReadKey();

}

}

abstract class State

{

public abstract void ShowCurrentState(Account account);

public void ShowCurrentLevel(Account account)

{

Console.WriteLine("Level:{0}", account.Level);

}

}

class FirstState:State

{

public override void ShowCurrentState(Account account)

{

if (account.Level >= 30)

{

account.CurrentState = new SecondState();

account.ShowCurrentState();

}

else

{

Console.WriteLine("Newbie Account...");

ShowCurrentLevel(account);

}

}

}

class SecondState : State

{

public override void ShowCurrentState(Account account)

{

if (account.Level < 30)

{

account.CurrentState = new FirstState();

account.ShowCurrentState();

}

else if (account.Level >= 60)

{

account.CurrentState = new ThirdState();

account.ShowCurrentState();

}

else

{

Console.WriteLine("Middle Account...");

ShowCurrentLevel(account);

}

}

}

class ThirdState : State

{

public override void ShowCurrentState(Account account)

{

if (account.Level < 60)

{

account.CurrentState = new SecondState();

account.ShowCurrentState();

}

else

{

Console.WriteLine("High Account...");

ShowCurrentLevel(account);

}

}

}

interface ISetState

{

void UpdateCurrentState(State currentState);

}

class Account:ISetState

{

public State CurrentState { get; set; }

public int Level { get; set; }

public Account()

{

CurrentState = new FirstState();

Level = 0;

}

public void UpdateCurrentState(State currentState)

{

CurrentState = currentState;

}

public void ShowCurrentState()

{

CurrentState.ShowCurrentState(this);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值