Question regarding use of the Factory pattern

Started by
13 comments, last by LorenzoGatti 12 years, 11 months ago
Well actually I did edit my post the second you replied to add the fact that you could use it to force interfaces onto the client code, so polymorphism would be used as a clean way of working with the returned objects, if that was your point?
Advertisement
Changed my mind. Read this: http://www.cs.qub.ac.uk/~P.Hanna/JavaProgramming/Lecture2/Java%20-%20Lecture%202%20-%20OOP%201.pdf

Well actually I did edit my post the second you replied to add the fact that you could use it to force interfaces onto the client code, so polymorphism would be used as a clean way of working with the returned objects, if that was your point?


If you're asking: Do factories provide a clean way of allowing "client code" to have knowledge of only interfaces, then the answer is Yes.

Without a factory, the code would have to do:


void MyFunc( )
{
// MyFunc has to know what a DerivedObject is.. it has to include its include file, and it has no flexibility regarding whether it creates DerivedType or DerivedType2
BaseObject * myObject = new DerivedObject();
}


If you're asking: Do factories provide a clean way of allowing "client code" to have knowledge of only interfaces, then the answer is Yes.
[/quote]

Yeah that was the direction I was going for ^^ By doing that you're ensuring that you only ever work with abstractions of the concrete objects that gets created by the factories, without having to know certain details of how it needs to be initialized and so forth.


Another important reason to use factories, which is likely to be relevant in a game, is ensuring coherence in covariant types that have expectations on the concrete types, and not only the public interface, of other objects created separately.
For example you could have a few interfaces to represent network stuff (Socket, Address, etc.) each with multiple implementations (e.g. IPv4 or IPv6). Trying to use an IPv6Socket with an IPv4Address would be an error: instead of creating concrete types like these directly and risking mismatches, you could rely on a NetworkStuffFactory (createSocket(), createAddress(), etc.) interface and choose in one place to use, say, a concrete Ipv6NetworkStuffFactory that creates compatible objects.

Omae Wa Mou Shindeiru

This topic is closed to new replies.

Advertisement