我正在学习GoF Java设计模式,我想看看它们的一些真实例子.Java核心库中这些设计模式的一些很好的例子是什么?
两种设计模式都封装了算法,并将实现细节与其调用类分离.我能辨别的唯一区别是策略模式接受执行参数,而命令模式则没有.
在我看来,命令模式要求所有执行信息在创建时都可用,并且它能够延迟其调用(可能作为脚本的一部分).
什么决定指导是使用一种模式还是另一种模式?
encapsulation design-patterns strategy-pattern command-pattern
我一直在阅读有关OCP主要内容以及如何使用策略模式来实现这一目标.
我打算尝试向几个人解释这个,但我能想到的唯一例子是根据"订单"的状态使用不同的验证类.
我在线阅读了几篇文章,但这些文章通常没有描述使用该策略的真实原因,如生成报告/账单/验证等...
是否有任何现实世界的例子,您认为策略模式是常见的?
任何人都可以用命令模式的简单例子来解释.我在互联网上提到但我很困惑.
我需要在求职面试中创建客户端 - 服务器程序,其中客户端发送命令并且服务器处理它们.
服务器需要能够轻松更改,这意味着以后可能会有更多的命令类型.
所以我使用Strategy实现它,这意味着类处理命令看起来类似于:
public class ServerProcessor
{
Dictionary<string, Action<string>> commandsType;
public ServerProcessor()
{
commandsType = new Dictionary<string, Action<string>>();
}
public void RegisterCommand(string commandName, Action<string> command)
{
commandsType.Add(commandName, command);
}
public void Process(string commandName, string vars)
{
if (commandsType.ContainsKey(commandName))
{
commandsType[commandName].Invoke(vars);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我这样做之后,面试官说我需要使用Command模式实现它,但没有说明原因.
Command模式将是这样的:
public interface ICommand
{
void Execute(string vars);
string GetName();
}
public class ServerProcessor2
{
List<ICommand> commandsType;
public ServerProcessor2()
{
commandsType = new List<ICommand>();
}
public void RegisterCommand(ICommand commandName)
{
commandsType.Add(commandName);
}
public void …Run Code Online (Sandbox Code Playgroud)