策略者模式(Strategy Pattern)
定义一系列算法, 并将每种算法分别放入独立的类中,让它们可以互相替换。
结构图:
角色:
- 上下文(Context): 包含策略接口的引用,通过策略接口与该对象进行交流。
- 策略(Strategy):所有具体策略的通用接口,给出所有具体策略类所需实现的接口。
- 具体策略(Concrete Strategies):实现了各种算法或行为。
适用场景:
- 许多仅在执行某些行为时有不同的相似类时,可使用策略模式。
- 避免冗长的 if-else 或 switch 分支判断。
优点:
- 策略之间可以自由切换。
- 新增策略不需要修改原有代码,符合开闭原则。
缺点:
- 策略类会变多,需要知道每个策略的用途然后才决定用哪一个。
代码(C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public interface ITravel { void TravelModel(); }
public class Car : ITravel { public void TravelModel() { Console.WriteLine("汽车"); } }
public class Train : ITravel { public void TravelModel() { Console.WriteLine("火车"); } }
public class TravelFactory { private Dictionary<string, ITravel> obj = new Dictionary<string, ITravel>();
public TravelFactory() { obj.Add("汽车", new Car()); obj.Add("火车", new Train()); }
public ITravel GetTravel(string type) { return obj[type]; } }
TravelFactory t = new TravelFactory(); var train=t.GetTravel("火车"); train.TravelModel();
|
最后
策略者模式看起来很像工厂模式,但是工厂模式是解耦对象的创建和使用。策略者模式解耦的是策略的定义、创建、使用这三部分。策略侧重如何灵活选择替换,工厂侧重怎么创建实例。