将系统中的相关 *** 作抽象成命令,使调用者与实现者相关分离.
类图 代码namespace 命令模式
{
internal class Program
{
static void Main(string[] args)
{
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);
Invoker i = new Invoker();
i.SetCommand(c);
i.ExecuteCommand();
Console.Read();
}
}
abstract class Command
{
protected Receiver receiver;
public Command(Receiver receiver)
{
this.receiver = receiver;
}
abstract public void Execute();
}
class ConcreteCommand : Command
{
public ConcreteCommand(Receiver receiver) : base(receiver)
{ }
public override void Execute()
{
receiver.Action();
}
}
class Invoker
{
private Command command;
public void SetCommand(Command command)
{
this.command = command;
}
public void ExecuteCommand()
{
}
}
class Receiver
{
public void Action()
{
Console.WriteLine("执行请求!");
}
}
}
职责链模式
概念
为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。
类图
代码
namespace 职责链模式
{
abstract class Handler
{
protected Handler successor;
public void SetSuccessor(Handler successor) //定义的顺序
{
this.successor = successor;
}
public abstract void HandleRequest(int request); //这里是处理请求的抽象方法
}
class ConcreteHandler1 : Handler //第一种具体处理的方法
{
public override void HandleRequest(int request)
{
if (request >= 0 && request < 10)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request); //如果请求不在0-10之间,且不为空,则转移到下一位,职责链的体现。
}
}
}
class ConcreteHandler2 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 10 && request < 20)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
else if (successor != null)
{
successor.HandleRequest(request); //如果请求不在10-20之间,且不为空,则转移到下一位,职责链的体现。
}
}
}
class ConcreteHandler3 : Handler
{
public override void HandleRequest(int request)
{
if (request >= 20)
{
Console.WriteLine("{0}处理请求{1}", this.GetType().Name, request);
}
}
}
class Program
{
static void Main(string[] args)
{
string FileValue = ConfigurationManager.AppSettings["num"]; //根据配置文件key值读取value值
string[] StringArray = FileValue.Split(','); //将字符串按照,号分割
List<Handler> handlerlist = new List<Handler>(); //创建一个Handler类型的list列表
for (int i = 0; i < StringArray.Length; i++) //执行一次添加一个对象
{
handlerlist.Add ( DataAccess.CreteHandler(StringArray[i])); //循环一次就往集合里添加一个对象类
}
for (int i = 1; i <= handlerlist.Count-1; i++) //设置了职责链的上下家,写活了
{
handlerlist[i-1].SetSuccessor(handlerlist[i]);
}
//handlerlist[0].SetSuccessor(handlerlist[1]);
//handlerlist[1].SetSuccessor(handlerlist[2]); //设置了职责链的上下家
int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };
foreach (int request in requests) //从requests这个数组里每次取一个int类型的数
{
handlerlist[0].HandleRequest(request);
}
Console.Read();
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)