Intro Strategy

Intro Strategy

Intro Strategy

Strategy

物件導向程式設計,並不是類別越多越好,類別的劃分是為了封裝,
但分類的基礎是抽象,具有相同屬性和功能之物件的抽象集合才是
類別。

策略模式(Strategy) 它定義了演算法家族,分別封裝起來,讓他們
之間可以互相替換,此模式讓演算法的變化,不會影響到使用演算法
的客戶。

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
46
47
48
49
50
51
52
53
54
55
56
abstract class Strategy
{
public abstract void AlgorithmInterface();
}


class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("演算法A實現");
}
}

class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("演算法B實現");
}
}

class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("演算法C實現");
}
}

class Context
{
public Context(Strategy strategy)
{
this.strategy = strategy;
}
public void ContextInterface()
{
strategy.AlgorithmInterface();
}
}

static void Main(string[] args)
{
Context context;
context = new Context(new ConcreteStrategyA());
context.ContextInterface();

context = new Context(new ConcreteStrategyB());
context.ContextInterface();

context = new Context(new ConcreteStrategyC());
context.ContextInterface();

Console.read();
}