我理解命令模式属于行为模式,简单工厂模式主要解决对象创建问题。但是当实现时我感觉两者都遵循类似的步骤。命令模式vs C简单工厂模式#
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");
}
}
我看不出有什么区别。有人能帮助我理解这一点吗?
事实上,你使用工厂模式来创建命令模式的命令并没有使另一个类似... –