Skip to content

Instantly share code, notes, and snippets.

@MeinLiX
Created June 7, 2021 10:31
Show Gist options
  • Select an option

  • Save MeinLiX/27a17213cb1c648554efd4912053fb00 to your computer and use it in GitHub Desktop.

Select an option

Save MeinLiX/27a17213cb1c648554efd4912053fb00 to your computer and use it in GitHub Desktop.
State Example .NET 5
using System;
try
{
Client server = new (new Idle());
server.Click();
server.Success();
server.Click();
server.Failure();
server.Retry();
server.Retry();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
class Client
{
public IApiState State { get; set; }
public Client(IApiState _state)
{
State = _state;
OnStateChange();
}
private void OnStateChange() => Console.WriteLine($"New state is {State.GetType()}");
public void Click()
{
State.Click(this);
OnStateChange();
}
public void Failure()
{
State.Failure(this);
OnStateChange();
}
public void Retry()
{
State.Retry(this);
OnStateChange();
}
public void Success()
{
State.Success(this);
OnStateChange();
}
}
class Utils
{
public static Exception IncorrectMoveException(IApiState _state) => new($"Incorrect move for state {_state.GetType()}");
}
interface IApiState
{
void Click(Client _client);
void Failure(Client _client);
void Retry(Client _client);
void Success(Client _client);
}
class Idle : IApiState
{
public void Click(Client _client) => _client.State = new Fetching();
public void Failure(Client _client) => throw Utils.IncorrectMoveException(this);
public void Retry(Client _client) => throw Utils.IncorrectMoveException(this);
public void Success(Client _client) => throw Utils.IncorrectMoveException(this);
}
class Fetching : IApiState
{
public void Click(Client _client) => throw Utils.IncorrectMoveException(this);
public void Failure(Client _client) => _client.State = new Error();
public void Retry(Client _client) => throw Utils.IncorrectMoveException(this);
public void Success(Client _client) => _client.State = new Idle();
}
class Error : IApiState
{
public void Click(Client _client) => throw Utils.IncorrectMoveException(this);
public void Failure(Client _client) => throw Utils.IncorrectMoveException(this);
public void Retry(Client _client) => _client.State = new Fetching();
public void Success(Client _client) => throw Utils.IncorrectMoveException(this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment