views:

46

answers:

1

Hi,

I've implemented an abstract factory like this

public abstract class AbstractFactory {

    private static final Map FACTORIES = new HashMap();    

    AbstractFactory(FactoryType type) {
        FACTORIES.put(type, this);
    }   

    public abstract A getA();

    public abstract B getB();

    public static AbstractCatalogFactory getFactory(FactoryType type) {
        return (AbstractCatalogFactory) FACTORIES.get(type);
    }
}

A concrete factory must call this abstract factories constructor, causing each concrete implementation to be registered in the FACTORIES map. I'm a bit concerned about referring to this within a constructor, because it seems like the value of this should be undefined until execution of the constructor has returned.

Thanks, Don

+2  A: 

About leaking this from the constructor

I'm a bit concerned about referring to this within a constructor, because it seems like the value of this should be undefined until execution of the constructor has returned.

More precisely, the this reference should not leak out of the constructor to external parties before the constructor finishes. Otherwise the external party might end up calling a method on the yet unfinished new object.

Your implementation has a chance of this happening, since this is added to the map, which is accessible by external parties via the static method getInstance. A remedy could be synchronizing access to the map. Another option (as discussed by Josh Bloch in Effective Java) would be to make the constructors in any concrete subclass private, and have a static factory method instead in each subclass, to construct the object, then add it to the map. This would result in some code duplication though.

About your design

Apparently you are implementing a "catalog of factories" rather than a "factory of products", so this is fairly different from the classic Abstract Factory. Without more details it's hard to tell whether or not this is justified.

The main issue is that here you unify the factory interface and the factory "storage", which is IMO not a good idea. Clients of the factory should only see the factory interface with its getX methods, and should not be aware of what concrete factory they are actually using (much less selecting it themselves).

Moreover, typically there is only one concrete family of products in use at any given time, so only one concrete kind of factory is needed. This eliminates the possibility of mixing up incompatible products from different concrete product families. Your current design seems to allow this, which is not a good sign to me - but maybe you have a good reason for this...

Péter Török
No it really is a factory of products, the Catalog is a bit of a misnomer, so i've removed it
Don