Re: How to implement Factory Pattern in Java

From: Andrew Hobbs (andrewh1_NoSpam__at_iinet.net.au)
Date: 01/20/04


Date: Tue, 20 Jan 2004 08:23:56 +0800


"Edward A Thompson" <ed4becky_2000@yahoo.com> wrote in message
news:d913df37.0401190802.b3bba43@posting.google.com...
> Is there any reason that the Factory Pattern cannot be implmented with
> a static getClass method in the base class?
>
> Rather than instantiate a factory, then call its getClass method (2
> steps):
>
> CalculatorFactory f = new CalculatorFactory ();
> Calculator c = f.getClass(someIndentifyingString);
>
> I was thinking of instantiating the final class I want by calling a
> static method in the base class:
>
> Calculator c = Calculator.getClass(someIndentifyingString);
>
> Is there a flaw in this strategy? What am I missing?

Your suggestion is hardly a factory method. Not that it won't work, but you
are starting to mix code for how to make calculators with their functional
code. Plus it means the base class has to have code relating to its derived
classes. None of this is a good idea.

However you can still have a single call to a static method such as

Calculator c = CalculatorFactory.getClass(someIndentifyingString);

This doesn't mean you can't have the advantages of an instantiated object.
Just make the Factory class hold a singleton of itself and make the static
method call on that singleton.

Andrew



Relevant Pages

  • Re: Unification of Methods and Functions
    ... I am suggesting that we write factory methods using classmethod to give ... my classes all implement an interface which I'll call 'shape ... Rectangle and Ellipse have a common base class, ...
    (comp.lang.python)
  • How to implement Factory Pattern in Java
    ... a static getClass method in the base class? ... Rather than instantiate a factory, then call its getClass method (2 ... CalculatorFactory f = new CalculatorFactory; ...
    (comp.lang.java.programmer)
  • Re: Factory method
    ... The base class must not create the children. ... If you don't want a public constructor, then define a Factory ... >I have an abstract class, and a set of classes that inherit from my ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Access subclass attributes from base
    ... factory object with the interface described earlier that implements more than ... The Instance property is the factory method that utilizes ... The subclasses only responsibility is to tell the base class to which ... super-generic base class contain it all. ...
    (microsoft.public.dotnet.framework.clr)
  • Re: Access subclass attributes from base
    ... generic factory using an attribute to specify the type of concrete class that will be implemented. ... You seem to have created the problem for yourself by insisting that a super-generic base class contain it all. ... This doesn't actually help the subclasses. ...
    (microsoft.public.dotnet.framework.clr)