publicclassOperaAdd : IStrategy { publicintDoOpera(int a, int b) { return a + b; } }
publicclassOperaSub : IStrategy { publicintDoOpera(int a, int b) { return a - b; } }
publicclassOperaMult : IStrategy { publicintDoOpera(int a, int b) { return a * b; } }
/************************策略模式*************************/ publicclassContext { private IStrategy strategy; publicContext(IStrategy strategy) { this.strategy = strategy; } publicintExecuteStrategy(int a, int b) { return strategy.DoOpera(a, b); } }
Context context = new Context(new OperaAdd()) context.ExecuteStrategy(1, 1); Context context = new Context(new OperaMult()) context.ExecuteStrategy(1, 1); /********************************************************/
/************************简单工厂*************************/ classOperaFactory{ publicstatic IStrategy GetOpera(string type){ IStrategy opera = null; if(type.EqualsIgnoreCase("+")){ opera = new OperaAdd(); } elseif(type.EqualsIgnoreCase("-")){ opera = new OperaSub(); } elseif(type.EqualsIgnoreCase("*")){ opera = new OperaMult(); } return opera; } }
IStrategy opera = ChartFactory.GetOpera("+"); opera.DoOprea(1, 1); /********************************************************/