C# 设计模式中的命令模式 问题求解~~

peng2739956 2011-03-17 07:18:26
刚刚看完了命令模式 写了个小小的例子 突然发现不改源码能变功能 但是要加功能的话 还得改源码 求解怎么不改源码添加功能
//发送者

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

namespace Command
{
public class Command_Sample01
{
public void Open()
{
Console.WriteLine("播放");
}
public void Close()
{
Console.WriteLine("暂停");
}
}
}

//功能实现

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

namespace Command
{
public class TVcloseCommand:AbstractCommand
{

private Command_Sample01 tv;
public TVcloseCommand()
{
tv = new Command_Sample01();
}
public void Execute()
{
tv.Close();
}


}
}


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

namespace Command
{
public class TvOpenCommand:AbstractCommand
{

#region AbstractCommand 成员
private Command_Sample01 tv;
public TvOpenCommand()
{
tv = new Command_Sample01();
}
public void Execute()
{
tv.Open();
}

#endregion
}
}

//接口

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

namespace Command
{
public interface AbstractCommand
{
void Execute();
}
}

//接收者

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

namespace Command
{
public class Controller
{
private AbstractCommand openCommand, CloseCommand;
public Controller(AbstractCommand openCommand, AbstractCommand CloseCommand)
{
this.openCommand = openCommand;
this.CloseCommand = CloseCommand;
}
public void Open()
{
openCommand.Execute();
}
public void Close()
{
CloseCommand.Execute();
}
}
}


//客户代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;
namespace Command
{
class Program
{
static void Main(string[] args)
{
AbstractCommand openCommand, CloseCommand;
string open = ConfigurationManager.AppSettings["TvOpenClass"];
openCommand = (AbstractCommand)Assembly.Load("Command").CreateInstance(open);
string Close = ConfigurationManager.AppSettings["TvCloseClass"];
CloseCommand = (AbstractCommand)Assembly.Load("Command").CreateInstance(Close);
//string Control = ConfigurationManager.AppSettings["Conntrol"];
//Controller control = (Controller)Assembly.Load("Command").CreateInstance(Control);
Controller control = new Controller(openCommand, CloseCommand);
control.Open();
control.Close();
Console.Read();
}
}
}

求解 加功能 不修改源码 怎么弄!
...全文
62 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2011-03-17
  • 打赏
  • 举报
回复
将更多的功能放入独立的dll

反射加载,转换成基类(或者接口),调用。

建议使用工厂模式。
cf370697816 2011-03-17
  • 打赏
  • 举报
回复
添加功能 肯定要加代码啊

110,546

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧