KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am a newbie and trying to understand concepts of inheritance and design patterns. I came across this pattern http://en.wikipedia.org/wiki/Strategy_pattern when I was going through some blog. I found it interesting and wanted to learn more. So I developed the following program. static void Main(string[] args) { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyAdd()); int resultA = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategySubtract()); int resultB = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategyMultiply()); int resultC = context.executeStrategy(3, 4); Console.Read(); } abstract class Strategy { public abstract int execute(int a, int b); public void Test() { Console.Write("tttt"); } } class ConcreteStrategyAdd : Strategy { public override int execute(int a, int b) { Console.WriteLine("Called ConcreteStrategyAdd's execute()"); return a + b; // Do an addition with a and b } } class ConcreteStrategySubtract : Strategy { public override int execute(int a, int b) { Console.WriteLine("Called ConcreteStrategySubtract's execute()"); return a - b; // Do a subtraction with a and b } } class ConcreteStrategyMultiply : Strategy { public override int execute(int a, int b) { Console.WriteLine("Called ConcreteStrategyMultiply's execute()"); return a * b; // Do a multiplication with a and b } } class Context { private Strategy strategy; // Constructor public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return strategy.execute(a, b); } } The program compiles fine and is workin
Tags (comma-separated)
Save Edits
Cancel