修饰模式(Decorator结构型)C#简单例子
修饰模式(Decorator结构型)C#简单例子
玩家基本功能是移动、运行等等。BaseAbility
新增加功能:1、伤害技能harmAbility;2、阻碍技能BaulkAbility;3、辅助技能assistAbility
玩家1增加伤害技能 Decorator harm = new HarmAbility(baseAbility);
玩家2增加伤害技能、阻碍技能 Decorator baulk = new BaulkAbility(harm);
玩家3增加伤害技能、阻碍技能和辅助技能 Decorator assist = new AssistAbility(baulk);
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
98
99
100
|
namespace adapterpattern { public partial class DecoratorForm : Form { public DecoratorForm() { InitializeComponent(); } private void btnDisplay_Click(object sender, EventArgs e) { BaseAbility baseAbility = new BaseOperation(); baseAbility.Run(); listBox1.Items.Add(baseData.baseString); baseData.baseString = "" ; listBox1.Items.Add( "***********玩家1新功能:伤害**************" ); Decorator harm = new HarmAbility(baseAbility); harm.Run(); listBox1.Items.Add(baseData.baseString); baseData.baseString = "" ; listBox1.Items.Add( "***********玩家2新功能:伤害和阻碍**************" ); Decorator baulk = new BaulkAbility(harm); baulk.Run(); listBox1.Items.Add(baseData.baseString); baseData.baseString = "" ; listBox1.Items.Add( "***********玩家3新功能:伤害、阻碍、辅助**************" ); Decorator assist = new AssistAbility(baulk); assist.Run(); listBox1.Items.Add(baseData.baseString); } } public abstract class BaseAbility //抽象的基础功能 { public abstract void Run(); } public class BaseOperation : BaseAbility //实体基础功能 { public override void Run() { baseData.baseString += "---移动---" ; baseData.baseString += "----运行----" ; } } public abstract class Decorator : BaseAbility //接口继承 { private BaseAbility baseAbility; //Has—A对象组合 public Decorator(BaseAbility baseAbility) //装饰连接点 { this .baseAbility = baseAbility; } public override void Run() { baseAbility.Run(); } } public class baseData //数据中转站 { public static string baseString { get; set; } } public class HarmAbility : Decorator //增加伤害技能 { public HarmAbility(BaseAbility baseAbility) : base(baseAbility) { } public override void Run() //增加伤害 { // base.Move(); base.Run(); baseData.baseString += "-----伤害-----" ; } } public class BaulkAbility : Decorator //增加阻碍技能 { public BaulkAbility(BaseAbility baseAbility) : base(baseAbility) { } public override void Run() //增加阻碍 { // base.Move(); base.Run(); baseData.baseString += "-----阻碍-----" ; } } public class AssistAbility : Decorator //增加辅助技能 { public AssistAbility(BaseAbility baseAbility) : base(baseAbility) { } public override void Run() { base.Run(); baseData.baseString += "-----辅助-----" ; } } } |