c#桥接模式(bridge结构模式)
桥接模式(bridge结构模式)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
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
|
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace adapterpattern { public partial class bridge : Form { public bridge() { InitializeComponent(); } private void btnDisplay_Click(object sender, EventArgs e) { play p1 = new play1(); p1.setPlayAction( new move()); p1.run(); this .listBox1.Items.Add(p1.playstring); play p2 = new play2(); p2.setPlayAction( new jump()); p2.run(); this .listBox1.Items.Add(p2.playstring); } } //意图(Intent)将抽象部分与实现部分分离,使它们都可以独立地变化。 public abstract class play //抽象部分 { public string playstring { get; set; } protected playAction pa; public void setPlayAction(playAction pa) //使用组合 { this .pa = pa; } public abstract void action(); //抽象部分变化 public void run() { pa.action(); //执行实现部分 action(); } } public class play1 : play { public override void action() { playstring = "play1" + pa.actionstring; } } public class play2 : play { public override void action() { playstring = "play2" + pa.actionstring; } } public abstract class playAction //对实现部分进行抽象 { public string actionstring; public abstract void action(); } public class move : playAction //实现玩家移动行为 { public override void action() { actionstring = "move" ; } } public class jump : playAction //实现玩家跳跃行为 { public override void action() { actionstring = "jump" ; } } } |