标题: Command模式
- Tony Zhou 2008-03-25 15:40 阅读:19
- 评论:0 | 添加评论
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Design_Pattern_Command : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Controller controller = new Controller();

        Hello hello = new Hello();
        HelloCommand helloCommand = new HelloCommand(hello);
        controller.SetCommand(0, helloCommand);

        Bye bye = new Bye();
        ByeCommand byeCommand = new ByeCommand(bye);
        controller.SetCommand(1, byeCommand);

        Good good = new Good();
        GoodCommand goodCommand = new GoodCommand(good);
        controller.SetCommand(2, goodCommand);

        controller.OnPush(2);
        controller.OnPush(0);
        controller.OnPush(1);

    }
}

public class Hello
{
    public void SayHello()
    {
        System.Web.HttpContext.Current.Response.Write("Hello!");
    }
}

public class Bye
{
    public void SayBye()
    {
        System.Web.HttpContext.Current.Response.Write("Bye!");
    }
}

public class Good
{
    public void SayGood()
    {
        System.Web.HttpContext.Current.Response.Write("Good!");
    }
}

public interface ICommand
{
    void Execute();
}

public class HelloCommand : ICommand
{
    private Hello _hello;

    public HelloCommand(Hello hello)
    {
        this._hello = hello;
    }

    public void Execute()
    {
        this._hello.SayHello();
    }
}

public class ByeCommand : ICommand
{
     private Bye _bye;

     public ByeCommand(Bye bye)
     {
        this._bye = bye;
     }

    public void Execute()
    {
        this._bye.SayBye();
    }
}

public class GoodCommand : ICommand
{
    private Good _good;

    public GoodCommand(Good good)
    {
        this._good = good;
    }

    public void Execute()
    {
        this._good.SayGood();
    }
}

public class Controller
{
    ICommand[] commands = new ICommand[3];

    public void SetCommand(int slot, ICommand command)
    {
        commands[slot] = command;
    }

    public void OnPush(int slot)
    {
        commands[slot].Execute();
    }
   
}

添加评论
返回顶部 | 返回首页