i am learning patterns and i got confused when i came across state and startegy pattern. A simple googling took me to this stact overflow blog which made to get confused even more.
My simple quesiton is,
strategy pattern
public interface Istrategy {
void algorithm();
}
public class add : Istrategy
{
public void algorithm()
{
Console.WriteLine("addition");
}
}
public class multiply : Istrategy
{
public void algorithm()
{
Console.WriteLine("multiply");
}
}
public class subtract : Istrategy
{
public void algorithm()
{
Console.WriteLine("subtract");
}
}
public class context {
public context(Istrategy strategy) {
strategy.algorithm();
}
}
public class client {
static void Main() {
new context(new add());
Console.ReadLine();
}
}
state pattern
public interface Istate {
void algorithm();
}
public class add : Istate
{
public void algorithm()
{
Console.WriteLine("addition");
}
}
public class multiply : Istate
{
public void algorithm()
{
Console.WriteLine("multiply");
}
}
public class subtract : Istate
{
public void algorithm()
{
Console.WriteLine("subtract");
}
}
public class context {
Istate state;
public context(Istate state) {
state.algorithm();
}
}
public class client {
static void Main() {
new context(new add());
Console.ReadLine();
}
}
in the above example, as per my understanding, i would take this as, passing a object to the context without any state saved is the strategy pattern and keeping the sate in the context is the state pattern.
is my understanding right?
UPDATE 1
interface Istate
{
void action();
}
class walk : Istate
{
public void action()
{
Console.WriteLine("walking !!!");
}
}
class run : Istate
{
public void action()
{
Console.WriteLine("running !!!");
}
}
class fly : Istate
{
public void action()
{
Console.WriteLine("flying !!!");
}
}
class context
{
Istate state;
public void statePattern()
{
for (var i = 0; i < 3; i++)
{
if (i == 0)
{
state = new walk();
state.action();
}
if (i == 1)
{
state = new run();
state.action();
}
if (i == 2)
{
state = new fly();
state.action();
}
}
}
}
public class client
{
static void Main()
{
new context().statePattern();
Console.ReadLine();
}
}
so as per my understanding, is this approach a state pattern and the approach below a strategy pattern?
interface Istate
{
void action();
}
class walk : Istate
{
public void action()
{
Console.WriteLine("walking !!!");
}
}
class run : Istate
{
public void action()
{
Console.WriteLine("running !!!");
}
}
class fly : Istate
{
public void action()
{
Console.WriteLine("flying !!!");
}
}
class context
{
public void statePattern(Istate state)
{
state.action();
}
public void startegy()
{
for (var i = 0; i < 3; i++)
{
if (i == 0)
{
statePattern(new walk());
}
if (i == 1)
{
statePattern(new run());
}
if (i == 2)
{
statePattern(new fly());
}
}
}
}
public class client
{
static void Main()
{
new context().startegy();
Console.ReadLine();
}
}
please let me know, thank you