您的位置:首页 > 编程语言 > C#

C# 设计模式之 职责链模式

2012-03-02 12:22 671 查看
每个职责类包含职责类对象,如果自己处理不了,交给职责类处理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPytternDemo
{

public abstract class DataTypeHandler
{
protected DataTypeHandler _handler;
public void SetHandler(DataTypeHandler handler)
{
this._handler = handler;
}

public abstract void Handle(object data);

}

public class IntHandler : DataTypeHandler
{

public override void Handle(object data)
{
if (data is int)
{
Console.WriteLine("int handler handle it!");
}
else
{
if (this._handler != null)
{
this._handler.Handle(data);
}
}
}
}

public class BoolHandler : DataTypeHandler
{
public override void Handle(object data)
{
if (data is bool)
{
Console.WriteLine("BoolHandler handler handle it!");
}
else
{
if (this._handler != null)
{
this._handler.Handle(data);
}
}
}
}

public class DoubleHandler : DataTypeHandler
{
public override void Handle(object data)
{
if (data is double)
{
Console.WriteLine("double handler handle it!");
}
else
{
if (this._handler != null)
{
this._handler.Handle(data);
}
}
}
}

}

DataTypeHandler bh1 = new IntHandler();
DataTypeHandler bh2 = new BoolHandler();
DataTypeHandler bh3 = new DoubleHandler();
bh1.SetHandler(bh2);
bh2.SetHandler(bh3);
int a = 1;
bool b = true;
double c = 1.2;
bh1.Handle(a);
bh1.Handle(b);
bh1.Handle(c);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息