开发者

How to make a constructor return a subclassed object

开发者 https://www.devze.com 2023-01-08 03:26 出处:网络
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 o

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 t开发者_如何学JAVAhe person, parses it, and returns the specific type of person that I want. Is this only possible with static factory methods?


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 of ClassName and not of a class that inherits from ClassName. So, you can't use new 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.


This is a paraphrase of Steven Sudit's comment

Create a Proxy class on top of the VillagePerson:

  • The Proxy implements the same interface as VillagePerson, but does not inherit any implementation code from it.
  • A Proxy contains a reference _vpImpl to a subclassed VillagePerson object.
  • When a method is called on the Proxy, the Proxy simply passes the call to the _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.

0

精彩评论

暂无评论...
验证码 换一张
取 消