修飾模式(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 +=
"-----輔助-----"
;
}
}
}