设计模式---职责链模式

2008年08月17日 星期日 下午 04:28

0dceef368c252b290b55a959.jpg

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
abstract class Officer
{
protected Officer myboss;

public Officer(Officer o)
{
myboss = o;
}

public abstract void Deal(Action a);
}

class PoliceMan : Officer
{
public PoliceMan(Officer o)
: base(o)
{
}

public override void Deal(Action a)
{
if (a == Action.逮捕罪犯)
{
Console.WriteLine("我是警察,我去逮捕罪犯");
}
else if (myboss != null)
{
myboss.Deal(a);
}
}
}

class FBI : Officer
{
public FBI(Officer o)
: base(o)
{
}

public override void Deal(Action a)
{
if (a == Action.暗杀)
{
Console.WriteLine("我是FBI,我去暗杀");
}
else if (myboss != null)
{
myboss.Deal(a);
}
}
}

class Precident : Officer
{
public Precident(Officer o)
: base(o)
{
}

public override void Deal(Action a)
{
if (a == Action.干掉萨达姆)
{
Console.WriteLine("我是总统,我去找人干掉萨达姆");
}
else if (myboss != null)
{
myboss.Deal(a);
}
}
}

enum Action
{
逮捕罪犯,
暗杀,
干掉萨达姆
}

class Client
{
public static void Main()
{
Officer police = new PoliceMan(new FBI(new Precident(null)));
police.Deal(Action.逮捕罪犯);
police.Deal(Action.暗杀);
police.Deal(Action.干掉萨达姆);
Console.Read();
}
}
}