Some times we want console application, when one screen changes other depend on user console read line input
Example:
Start:
user select P:
user select M:
User select P:
User Select F:
It is very easy do with using State design pattern.
Solution:
Classes:
Program.cs:
class Program
{
static void Main(string[] args)
{
IState state = new MainMenuState();
Context context = new Context(state);
while (true)
{
context.Request();
}
}
}
Example:
Start:
user select P:
user select M:
User select P:
It is very easy do with using State design pattern.
Solution:
Classes:
Program.cs:
class Program
{
static void Main(string[] args)
{
IState state = new MainMenuState();
Context context = new Context(state);
while (true)
{
context.Request();
}
}
}
Context.cs:
public sealed class Context
{
public Context(IState state)
{
State = state;
}
public IState State { get; set; }
public void Request()
{
State.PrintOptions();
string userChoise = Console.ReadLine();
State.UpdateState(this, userChoise);
}
}
IState.cs:
public interface IState
{
void PrintOptions();
void UpdateState(Context context, string userChoise);
}
}
State classes:
public sealed class MainMenuState : IState
{
public void PrintOptions()
{
Console.Clear();
Console.WriteLine("Hello. Is Main menu");
Console.WriteLine("P - print hello");
}
public void UpdateState(Context context, string userChoise)
{
switch (userChoise)
{
case "P":
context.State = new PrintHelloState();
break;
}
}
}
public class PrintHelloState : IState
{
public void PrintOptions()
{
Console.Clear();
Console.WriteLine("Hello my little friend!");
Console.WriteLine("M - main menu");
Console.WriteLine("F - finish menu");
}
public void UpdateState(Context context, string userChoise)
{
switch (userChoise)
{
case "M":
context.State = new MainMenuState();
break;
case "F":
context.State = new FinishMenuState();
break;
}
}
}
public sealed class FinishMenuState : IState
{
public void PrintOptions()
{
Console.Clear();
Console.WriteLine("Bye Bye");
Thread.Sleep(1000);
Console.WriteLine("See you");
Thread.Sleep(1000);
Environment.Exit(0);
}
public void UpdateState(Context context, string userChoise)
{
}
}
Also, some functionality can be added in one of overloaded function, or added new one.
No comments:
Post a Comment