Smalltalk 相当于工厂方法吗?
Smalltalk 中是否使用了工厂方法?如果是,那么应该如何编写工厂方法,而不是在 Java 中使用工厂方法? 谢谢。
Are factory methods used in Smalltalk, and if so, how should one go about writing one, as opposed to how they would in Java, for example?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在工厂模式中,我们实例化一些子类而不命名它。考虑一个披萨工厂和层次结构:
我们想实例化一个披萨子类,而不知道它的类名。例如:
回答披萨的正确子类,并填写其大小。
现在,在 Java 或 C++ 中,人们可能会执行一个大的“switch”语句来比较不同的字符串名称。每次我们添加 Pizza 的新子类时,我们都需要记住添加到主 switch 语句中。请参阅维基百科文章了解典型示例。
在 Smalltalk 中情况并非如此,其中类是第一类对象,因此我们可以向下迭代类层次结构,要求每个子类进行匹配。例如:
每当我们实现披萨的新子类时,我们都会实现一种方法来进行工厂匹配:
无需维护中央 switch 语句。只是物体!
In a factory pattern we instantiate some subclass without naming it. Consider a pizza factory and hierarchy:
We'd like instantiate a pizza subclass without knowing it's class name. For example:
answers the right subclass of pizza, with it's size filled in.
Now in Java or C++ one would probably do a large 'switch' statement to compare on different string names. Each time we added a new subclass of Pizza, we'd need to remember to add to the master switch statement. See Wikipedia article for typical examples.
Not so in Smalltalk, where classes are first class objects, so we can iterate down the class hierarchy, asking each subclasses to match. For example:
And whenever we implement a new subclass of pizza, we implement one method to do the factory matching:
No central switch statement to maintain. Just objects!
首先,在 Smalltalk 中您已经命名了构造函数。事实上,类是对象,“构造函数”只是在类上定义的方法,这些方法恰好返回新实例。其他语言中工厂方法的许多用法都可以通过这种方式涵盖。
例如,
它通过名称获取一个事物,并且仅当具有该名称的事物尚不存在时才创建一个新事物。
First of all, in Smalltalk you have named constructors. In fact, classes are objects and "constructors" are just methods defined on the class that happen to return new instances. Many uses of factory methods in other languages can be covered that way.
For example
which get a thing by name, and only creates a new thing if a thing with that name does not yet exist.