单一使用的类与“静态类”
我有一个程序可以处理不同的对象,这些对象有自己的指令集(比如它们自己的程序),并且我想从主类中运行这些程序。然后我有两个选择:
- 创建一个类InstructionHandler,在我的主类中创建它的一个实例,并将请求传递给该对象[单例模式-感谢Mark Peters]
- 创建一个仅包含静态方法的类InstructionHandler,并在我的主课
从软件设计的角度来看,什么是好方法?
I have a program that handles different objects which have their own sort of instructions set (say their own program), and from a main class I want to run these programs. Then I have two choices:
- Make a class InstructionHandler, create an instance of it in my main class and pass requests to that one object [Singleton pattern - thanks to Mark Peters]
- Make a class InstructionHandler with just static methods and make use of these in my main class
What would be the good way to go from a software - design point of view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否考虑过使用解释器模式?是否可以组合每个对象的指令集来创建某种语法?
Have you considered using the Interpreter Pattern? Can the instruction sets be combined for each of the objects to create some kind of grammar?
使用 Singleton 会更好。如果您曾经(例如为了测试)想要更改系统的行为,静态方法会干扰它。使用单例,您可以简单地子类化并覆盖相关方法,然后使用子类的实例代替常规类实例。静态方法不可能进行此类替换。
You are much better off with a Singleton. If you ever (for testing, for instance) wanted to change the behavior of your system, static methods interfere with it. With a Singleton, you can simply subclass and override the method(s) of concern, then use an instance of the subclass in place of your regular class instance. No such substitution is possible with static methods.