I am talking about the Strategy pattern. Why are we complicating everything? Why do we need the Context class at all? We could simply use the inheritance mechanism. This is an example of Strategy pattern:
public interface IChoice
{
void SetChoice();
}
public class FirstChoice : IChoice
{
public void SetChoice()
{
Console.WriteLine(@"Traveling to Japan");
}
}
public class SecondChoice : IChoice
{
public void SetChoice()
{
Console.WriteLine(@"Traveling to India");
}
}
public class Context
{
IChoice _choice;
public void SetChoice(IChoice choice)
{
_choice = choice;
}
public void ShowChoice()
{
_choice.SetChoice();
}
}
And from Client:
var cxt = new Context();
for (var i = 1; i <= 2; i++)
{
Console.WriteLine(@"\nEnter ur choice(1 or 2)");
string c = Console.ReadLine();
IChoice ic;
if (c != null && c.Equals("1"))
{
ic = new FirstChoice();
}
else
{
ic = new SecondChoice();
}
cxt.SetChoice(ic);
cxt.ShowChoice();
}
We could simply use the inheritance mechanism. Why do we need the Context class at all? One of the problems with inheritance mechanism, is this scenario: when we want to introduce another class in our system that has a special choice, for instance MySpecialChoice()
, we clearly should not add it in the IChoice
interface because all the existing classes need to implement this additional method, but for this challenge we have a solution like this: we could simply use Interface Segregation principle of SOLID, I mean, create a separate interface, say ISpecialChoice
, and place the MySpecialChoice()
method in that interface. Now any class that wants to get the method can implement that interface also. So what is the usage of the Context
class? And if this is not a good solution for this challenge, how Context
class will handle it?
Aucun commentaire:
Enregistrer un commentaire