Chain Of Responsibility 避免把一个请求的发送者和请求者的接收者进行耦合,这个模式要求多个对象都有机会处理这个请求
1
Console.WriteLine( root.Responsible.Name );2
Console.WriteLine( leafoneleft.Responsible.Name );3
Console.WriteLine( leafoneright.Responsible.Name );4
Console.WriteLine( leaftwoleft.Responsible.Name );5
Console.WriteLine( leaftworight.Responsible.Name );6
Console.ReadLine();1
using System;2

3
namespace Gof.Test.ChaninOfResponsibility4


{5
public abstract class MachineComponent6

{7
public MachineComponent(MachineComponent parent)8

{9
_parent = parent; 10
}11
public MachineComponent(MachineComponent parent,Engineer responsible):this(parent)12

{13
_responsible = responsible;14
}15
public virtual MachineComponent Parent16

{17
get18

{19
return _parent;20
}21
}private MachineComponent _parent;22
public virtual Engineer Responsible23

{24
get25

{26
if( _responsible != null)27

{28
return _responsible;29
}30
return Parent.Responsible;31
} 32
}private Engineer _responsible;33
}34
}1
using System;2

3
namespace Gof.Test.ChaninOfResponsibility4


{5
public class MachineComposite:MachineComponent6

{7
public MachineComposite(MachineComponent parent):base(parent)8

{}9
public MachineComposite(MachineComponent parent,Engineer responsible):base(parent,responsible)10

{}11
}12
}1
using System;2

3
namespace Gof.Test.ChaninOfResponsibility4


{5
public class Machine:MachineComponent6

{7
public Machine(MachineComponent parent):base(parent)8

{ }9
public Machine(MachineComponent parent,Engineer responsible):base(parent,responsible)10

{ }11
}12
}1
using System;2

3
namespace Gof.Test.ChaninOfResponsibility4


{5
public class MachineRoot:MachineComposite6

{7
public MachineRoot(Engineer responsible):base(null,responsible)8

{9
}10
public override MachineComponent Parent11

{12
get13

{14
throw new Exception("根节点没有上一级");15
}16
}17

18
}19
}1
using System;2

3
namespace Gof.Test.ChaninOfResponsibility4


{5
public class Engineer6

{7
public Engineer(string name)8

{9
_name = name;10
}11
public string Name12

{13
get14

{15
return _name;16
}17
set18

{19
_name = value;20
}21
}private string _name = string.Empty; 22
}23
}

浙公网安备 33010602011771号