这种情况的命令模式?建议
大家晚上好。我一直在阅读命令模式,我想知道它是否适合我想要构建的内容。
本质上,我有一个与服务器形成套接字连接的客户端。我的服务器上有 1 个类“foo”,客户端需要对其调用方法。
假设 foo 有 5 个我的客户端将调用的方法。我过去犯过一个错误,即编组在服务器上编组的对象。然后我检查对象中的变量并使用 switch 语句,服务器逻辑可以确定应该调用什么操作。
我想避免这种情况,所以我相信命令模式可能对我有帮助。但是,对于服务器上的示例“foo”类,我是否需要为要在 foo 中调用的每个方法创建一个命令类?从客户端发送到服务器的类应该是命令类吗?在这种情况下我只需要 1 个接收器吗? - foo 类?
非常感谢您的帮助,并对这里的“foo”类名称感到抱歉。我还没有任何具体的类名!
此致
good evening all. ive been reading up on the command pattern and im wondering if it's a good fit for what i want to build.
essentially, i have a client that forms a socket connection with a server. there is 1 class 'foo' on my server that the client needs to invoke methods against.
lets say foo has 5 methods that my client will invoke. i have made the mistake in the past of marshalling an object that is demarshalled on the server. then i check a variable in the object and using a switch statement, the server logic can determine what action should be invoked.
i want to avoid this and so i believe the command pattern may help me. but, for my example 'foo' class on the server, do i need to create a command class for each method that is to be invoked in foo? should the class that is sent from the client to the server be a command class? will i only need 1 receiver in this case? - the foo class?
thanks very much for your help and sorry about the 'foo' class name here. i havent got any concrete class names yet!
best regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无论你做什么,你都无法完全摆脱 switch() 语句。命令模式建议您执行以下操作:
然后您有一个命令工厂:
您的消息接收部分变得像这样简单:
这样做的好处是您可以将命令的实际逻辑(execute() 方法实现)与决定使用哪个命令的逻辑,来自知道如何在网络上接收消息的逻辑。
No matter what you do, you will not be able to entirely get rid of that switch() statement. Command pattern would suggest you do the following:
Then you have a command factory:
And your message receiving part becomes as simple as this:
What's nice about this is that you cleanly separate the actual logic of commands (execute() method implementations) from the logic that decides which command to use, from the logic that knows how to receive messages on the network.