Я понял, что командный шаблон относится к поведенческому шаблону, а простой шаблон фабрики решает главным образом проблемы с созданием объекта. Но когда приходит к реализации, я чувствую, что оба следует аналогичным шагам.командный шаблон 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");
}
}
Я не видел никакой разницы в реализации. Может ли кто-нибудь помочь мне понять это?
Тот факт, что вы использовали шаблон фабрики для создания команд для шаблона команд, не делает одно похожее на другое ... –