据我所知,命令模式属于行为模式,简单的工厂模式主要解决对象创建问题。但到了实现阶段,我觉得两者都遵循着类似的步骤。
public interface ICommand
{
string Name { get; }
void Execute();
}
public class StartCommand : ICommand
{
public void Execute()
{
Console.WriteLine("I am executing StartCommand");
}
public string Name
{
get { return "Start"; }
}
}
public class StopCommand : ICommand
{
public void Execute()
{
Console.WriteLine("I am executing StopCommand");
}
public string Name
{
get { return "Stop"; }
}
}
public class Invoker
{
ICommand cmd = null;
public ICommand GetCommand(string action)
{
switch (action)
{
case "Start":
cmd = new StartCommand();
break;
case "Stop":
cmd = new StopCommand();
break;
default:
break;
}
return cmd;
}
}
class Program
{
static void Main(string[] args)
{
Invoker invoker = new Invoker();
// Execute Start Command
ICommand command = invoker.GetCommand("Start");
command.Execute();
// Execute Stop Commad
command = invoker.GetCommand("Stop");
command.Execute();
Console.WriteLine("Command Pattern demo");
Console.Read();
}
}这是一个简单工厂模式的例子。
interface IGet
{
string ConC(string s1, string s2);
}
class clsFirst : IGet
{
public string ConC(string s1, string s2)
{
string Final = "From First: " + s1 + " and " + s2;
return Final;
}
}
class clsSecond : IGet
{
public string ConC(string s1, string s2)
{
string Final = "From Second: " + s1 + " and " + s2;
return Final;
}
}
class clsFactory
{
static public IGet CreateandReturnObj(int cChoice)
{
IGet ObjSelector = null;
switch (cChoice)
{
case 1:
ObjSelector = new clsFirst();
break;
case 2:
ObjSelector = new clsSecond();
break;
default:
ObjSelector = new clsFirst();
break;
}
return ObjSelector;
}
}
class Program
{
static void Main(string[] args)
{
IGet ObjIntrface = null;
int input = Convert.ToInt32(Console.ReadLine());
ObjIntrface = clsFactory.CreateandReturnObj(input);
string res = ObjIntrface.ConC("First", "Second");
}
}我看不出在实现上有什么不同。有人能帮我理解这一点吗?
发布于 2016-09-17 02:21:22
Invoker是工厂模式,但不是命令:
public interface ICommandFactory
{
ICommand CreateCommand(string action);
}
public class Invoker : ICommandFactory
{
public ICommand CreateCommand(string action)
{
...
}
}命令模式是一种行为设计模式,在这种模式中,对象用于封装执行操作或稍后触发事件所需的所有信息。
因此,您的StartCommand和StopCommand类只实现命令模式。
更新
在第二个示例中,您实现了一个简单的工厂,clsFirst和clsSecond不是命令,因为它们的命名并不意味着捕获任何输入或执行操作的上下文--它们只是实现相同接口的类。您必须有一个逻辑的Invoke或Execute方法,它意味着对某项操作的操作(有时您可以撤销该操作)。但是,如果你不是人,而是某种人工智能,那么IGet和string ConC(string s1, string s2)完全可以是命令的定义,也可以是你的动作:)
再一次,工厂和命令之间没有任何共同点。您可以使用工厂创建命令,但它是可选的。除了命令之外,您还可以使用工厂创建任何东西。
https://stackoverflow.com/questions/39542239
复制相似问题