views:

52

answers:

2

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?

+3  A: 

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.

Victor Nicollet
+1 for the caveat about dynamically typed languages
MikeD
Your answer is correct, but there are ways to approximate dynamic typing even in statically-typed languages. For example, the `VillagePerson` constructor can call a `VillagePersonImplFactory` static factory method to initialize its `_vpImpl` member. Then, when its `Dance` method is called, it can chain the call to `_vpImpl`. I'm sure the GoF design patterns book has some official label for this; I think something about templates.
Steven Sudit
@Steven Sudit: Yes. I do find using a factory method easier, though.
Victor Nicollet
+1  A: 

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.

rwong
Clever. Seems like a lot of work thought.
John Berryman
It is a paraphrase of Steven Sudit's comment.
rwong