您的位置:首页 > 其它

设计模式---职责链模式

2008-08-18 18:46 381 查看
 
2008年08月17日 星期日 下午 04:28

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    abstract class Officer
    {
        protected Officer myboss;
        public Officer(Officer o)
        {
            myboss = o;
        }
        public abstract void Deal(Action a);
    }
    class PoliceMan : Officer
    {
        public PoliceMan(Officer o)
            : base(o)
        {
        }
        public override void Deal(Action a)
        {
            if (a==Action.逮捕罪犯)
            {
                Console.WriteLine("我是警察,我去逮捕罪犯");
            }
            else if(myboss!=null)
            {
                myboss.Deal(a);
            }
        }
    }
    class FBI : Officer
    {
        public FBI(Officer o)
            : base(o)
        {
        }
        public override void Deal(Action a)
        {
            if (a == Action.暗杀)
            {
                Console.WriteLine("我是FBI,我去暗杀");
            }
            else if (myboss != null)
            {
                myboss.Deal(a);
            }
        }
    }
    class Precident : Officer
    {
        public Precident(Officer o)
            : base(o)
        {
        }
        public override void Deal(Action a)
        {
            if (a == Action.干掉萨达姆)
            {
                Console.WriteLine("我是总统,我去找人干掉萨达姆");
            }
            else if (myboss != null)
            {
                myboss.Deal(a);
            }
        }
    }
    enum Action
    {
        逮捕罪犯,
        暗杀,
        干掉萨达姆
    }
    class Client
    {
       
        public static void Main()
        {
            Officer police = new PoliceMan(new FBI(new Precident(null)));
            police.Deal(Action.逮捕罪犯);
            police.Deal(Action.暗杀);
            police.Deal(Action.干掉萨达姆);
            Console.Read();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息