views:

151

answers:

6

What is the advantage to have all my classes instantiated only through the Factory DP?

As far as know a Factory is good when you have to choose from a list of similar objects to perform some task,let's say like translations classes (english-> franch, arab->hebrew ...) But when you have really one possible option, no reason to obscure/abstract the logic with a Factory method.

Any insights?

+1  A: 

You probably don't want all of your classes to be coming from a hand-written factory. Dependency injection might be more useful, you can write objects and whatever DI framework you use can just populate your objects for you. If you fully utilize DI, the number of "new" calls in your code will go way down.

We use Spring a lot, and Spring.NET, but there are many other options too.

Andy White
+1  A: 

How do you know, that there won't be other possibilities in the future? One of the most often reasons to change implementation of dependency is for unit tests. Do you really want all dependencies to use their real implementations when you are writing unit tests for it? Perfectly when writing a class you would declare what it needs to get its work done as arguments in the constructor, without caring where the implementations come from.

Using factories is one option to do this, better is to use a Dependency Injection container. There are quite few open source containers - pick one that suits your needs.

devdimi
+2  A: 

One general advantage of factory methods is that you can control object creation behind the public interface. So without affecting client code, you could add things like caching mechanisms later.

Fabian Steeg
+1  A: 

One use of the factory pattern is to overcome the constructor limitations that you find in languages like Java and C#:

  1. A constructor can only return an instance of its associated class, never a subtype - even though a subtype would be acceptable, by definition.

  2. A constructor must always return a new object, never a previously allocated object. This can be annoying - for example, there is really no need to have multiple instances of equal immutable objects.

Jordão
+2  A: 

Write your code simply at first: use constructors. If you find constructors are limiting you later, refactor at that point to use a factory. Avoid speculative design: it adds complexity with little real value.

munificent