When an action has multiple implementation methods, you need to select a method to execute the action based on the actual situation, you can consider using the Policy mode.
Abstract actions into interfaces, such as playing balls into interfaces.
public interface IBall
{
void Play();
}
It may be playing football, basketball, volleyball, etc. These balls are abstracted into classes that implement interfaces.
public class Football : IBall
{
public void Play()
{
Console. writeline ("I like football ");
}
}
public class Basketball : IBall
{
public void Play()
{
Console. writeline ("I like basketball ");
}
}
public class Volleyball : IBall
{
public void Play()
{
Console. writeline ("I like volleyball ");
}
}
Another class is specifically used to select the ball and execute the interface method.
public class SportsMan
{
private IBall ball;
public void SetHobby(IBall myBall)
{
ball = myBall;
}
public void StartPlay()
{
ball.Play();
}
}
The client needs the user to make a choice and instantiate a specific class according to different options.
class Program
{
static void Main(string[] args)
{
IBall ball = null;
SportsMan man = new SportsMan();
while (true)
{
Console. writeline ("select your favorite ball games (1 = football, 2 = Basketball, 3 = volleyball )");
string input = Console.ReadLine();
switch (input)
{
case "1":
ball = new Football();
break;
case "2":
ball = new Basketball();
break;
case "3":
ball = new Volleyball();
break;
}
man.SetHobby(ball);
man.StartPlay();
}
}
}
Use the simplest example to understand the strategy Pattern)