设计模式 <行为型> | 策略者模式

策略者模式(Strategy Pattern)

定义一系列算法, 并将每种算法分别放入独立的类中,让它们可以互相替换。

结构图:

角色:

  1. 上下文(Context): 包含策略接口的引用,通过策略接口与该对象进行交流。
  2. 策略(Strategy):所有具体策略的通用接口,给出所有具体策略类所需实现的接口。
  3. 具体策略(Concrete Strategies):实现了各种算法或行为。

适用场景:

  1. 许多仅在执行某些行为时有不同的相似类时,可使用策略模式。
  2. 避免冗长的 if-else 或 switch 分支判断。

优点:

  1. 策略之间可以自由切换。
  2. 新增策略不需要修改原有代码,符合开闭原则。

缺点:

  1. 策略类会变多,需要知道每个策略的用途然后才决定用哪一个。

代码(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
// 策略(Strategy)
public interface ITravel
{
void TravelModel();
}

// 具体策略(Concrete Strategies)
public class Car : ITravel
{
public void TravelModel()
{
Console.WriteLine("汽车");
}
}

// 具体策略(Concrete Strategies)
public class Train : ITravel
{
public void TravelModel()
{
Console.WriteLine("火车");
}
}

// 上下文(Context)
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();

最后

策略者模式看起来很像工厂模式,但是工厂模式是解耦对象的创建和使用。策略者模式解耦的是策略的定义、创建、使用这三部分。策略侧重如何灵活选择替换,工厂侧重怎么创建实例。


设计模式 <行为型> | 策略者模式
http://example.com/posts/50248.html
作者
她微笑的脸y
发布于
2023年3月8日
许可协议