如何使构造函数返回子类对象
我刚刚读了一本关于面向对象编程模式的书。它描述了一种工厂模式,您可以通过该模式调用对象的静态工厂方法,并且该对象将返回预期类型的新对象,但它将被适当地子类化。
我的问题是,这个功能可以由类的构造函数提供吗?如果是这样怎么办?如果不是为什么?想象一下,我有一个名为 VillagePerson 的类,它有子类 PoliceOfficer、NativeAmerican、Cowboy、Biker、ConstructionWorker 和 Sailor。构造函数获取人员的文本字符串描述,对其进行解析,然后返回我想要的特定类型的人员。这只能通过静态工厂方法实现吗?
I just read a book on object-oriented programming patterns. It describes a Factory pattern by which you can make a call to a static factory method of an object and the object will return a new object of expected type, but it will be subclassed appropriately.
My question, can this functionality be provided by a constructor for the class? If so how? I f not why? Imagine I have a class called VillagePerson, which has subclasses PoliceOfficer, NativeAmerican, Cowboy, Biker, ConstructionWorker, and Sailor. The constructor takes a text string description of the person, parses it, and returns the specific type of person that I want. Is this only possible with static factory methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
否。通常,构造函数是由语言自动调用的函数,用于初始化正在创建的对象。这本身意味着工厂的“叫我创建对象”功能不能由构造函数提供。
此外,构造函数通常从诸如
new ClassName(args)
之类的表达式中调用,这些表达式在大多数语言中定义为创建ClassName
的实例,而不是从继承的类的实例>类名
。因此,您不能使用 new 或构造函数来创建任何类型的实例。另一方面,我确实说过“在大多数语言中”:有些语言(例如 JavaScript)允许您从构造函数中返回任何想要的内容,而另一些语言(例如 Objective Caml)则将构造函数视为工厂函数。
No. Usually, a constructor is a function that is called automatically by the language to initialize an object that is being created. This, in itself, means that the "call me to create an object" functionality of factories cannot be provided by a constructor.
Also, constructors are usually called from expressions like
new ClassName(args)
which are defined in most languages as creating an instance ofClassName
and not of a class that inherits fromClassName
. So, you can't usenew
or constructors to create instances of any type.On the other hand, I did say "in most languages" : some, like JavaScript, let you return anything you want out of a constructor, and others, like Objective Caml, treat constructors as factory functions.
这是 Steven Sudit 评论的释义
创建一个 Proxy 类
VillagePerson
顶部:VillagePerson
相同的接口,但不继承任何实现代码。_vpImpl
。_vpImpl
对象。要构造子类
VillagePerson
,Proxy 的构造函数可以调用子类的特定构造函数,然后将其存储在_vpImpl
中。This is a paraphrase of Steven Sudit's comment
Create a Proxy class on top of the
VillagePerson
:VillagePerson
, but does not inherit any implementation code from it._vpImpl
to a subclassed VillagePerson object._vpImpl
object.To construct a subclassed
VillagePerson
, the Proxy's constructor could call the specific constructor of the subclass and then store it in_vpImpl
.