Factory Method

See: FactoryMethodPattern

See also: FactorySystem


So another fellow I was discussing patterns with decided that my rather HandWaving definition of a factory method (something that looks like it gets you an object you didn't have before) was far too imprecise, and often just dead wrong. I freely admitted that I would call things that didn't actually create new objects, "factory methods". He said I should stop this.

So here's my question. Assume that an EmailAddress is a immutable object. I have these three methods in my EmailAddress class:

    public EmailAddress create1(String address) {
return new EmailAddress(address);
    }

private Map _cache = new HashMap(); public EmailAddress create2(String address) { EmailAddress em = _cache.get(address); if (em != null) return em; em = new EmailAddress(address) _cache.put(address, em); return em; }

public EmailAddress create3(String address) { // The implementation of this method is a secret, but it adheres // to the obvious contract. If invoked twice with the same parameter, // retval1.equals(retval2) will always be true. }
In the examples above, probably everyone agrees that create1 is a factory method. I just wave my arms and call them all factory methods. Is create2 a factory method? Is create3? Do we even care?


I think I agree with your friend: I wouldn't call any of your methods FactoryMethods. The pattern specifies abstract Product and Creator classes which define the interface to use. Then you have ConcreteProduct? classes that are created by ConcreteCreator? classes. To continue with the idea of email addresses, suppose EmailAddress is your abstract product class, and Application is your abstract creator class (that's lame, I know: sorry). Then let's say you have two programs that send email, one that uses SMTP called SMTPApplication, and one that uses UUCP, called UUCPApplication, and two concrete email address classes, UUCPAddress and SMTPAddress:

    abstract class EmailAddress {

// details

}

public class SMTPAddress extends EmailAddress {

public SMTPAddress(String addr) { // create address }

// ...

}

abstract class Application {

abstract EmailAddress createEmailAddress(String addr) ;

// other methods ...

}

public class SMTPApplication extends Application {

public EmailAddress createEmailAddress(String addr) { return new SMTPAddress(addr) ; }

// ...

}
The difference is that while your methods are creational, the complexity is not present to justify calling this an example of a design pattern, or even needing a pattern.

I believe that one of the main reasons for this pattern is to implement a framework across a wide variety of implementations. Rather than providing better encapsulation, or code structure, this pattern tends to make different applications follow a similar framework, and thus make them easier to understand.

I hope this all makes sense: I'm rather new to design patterns.


In the examples above, probably everyone agrees that create1 is a factory method. I just wave my arms and call them all factory methods. Is create2 a factory method? Is create3?

All of them can be called factory methods. Clients expect an object, and do not care whether it is new or cached.

However, there may be cases when it is good to advertise whether the method creates or caches. -- ManuelSimoni


So one person says that none of them is FactoryMethods and another says that all of them are. Which is it??


They are all factory methods.

They do not (collectively) represent an AbstractFactory pattern. Half the idea of FactoryMethod is to hide object instantiation/creation/construction so that the class manages. Techniques like object uniquing or for that matter, support for the SingletonPattern are completely valid and don't remove status from a FactoryMethod. The pattern describes the interface, not the implementation, so questions about whether a new object is created (implementation), can't/don't apply to the question of whether some collection of methods follow FactoryMethod pattern.


I say they are all Factories. I think Manuel is correct in asserting that it doesn't matter whether the objects are cached or not. Clients call on the Factory to get an object. The 'newness' of the object should not be a factor.


I think the confusion here is that we are talking about FactoryMethodPattern. FactoryMethodPattern is different from FactoryMethod or CreationMethod. create1, create2, create3 are examples of CreationMethod or FactoryMethod and not FactoryMethodPattern. In the factory method pattern, it is the subclass that decides which classes to instantiate. -- GunjanDoshi


Is this correct? The Gang of Four book says that the FactoryMethod is used to 'define an interface for creating an object, but let subclasses decide which class to instantiate'. How is this different from FactoryMethodPattern, surely they're the same?

If FactoryMethod is the pattern as described in the book then none of the first three examples are FactoryMethods?. They simply create objects and do not implement any pattern. BuildMeA() below is not a FactoryMethod either, maybe it's just a factory. The SMTPApplication example is a correct FactoryMethod. -- Ita


If the only criteria here is that a method have the statement "return new <whatever>", then yes, these can be considered factory methods (they do, after all create a new object and return it). I tend to think of a factory method as a method that could return different objects based on run-time conditions. In your create methods you are always returning an object of type EmailAddress? (not too interesting :( ). I think the example we are working with here is a poor one to really get a feel of what factory methods are supposed to do. There is only one type of email address, and it is simply a string. The following method illustrates how I have thought of factory methods:

    public Computer BuildMeA(String type) {
        if(type.equals("MAC"))
            return new Mac();
        if(type.equals("PC"))
            return new Pc();
        if(type.equals("Next"))
            return new Next();
        // etc...
    }
Mac,Pc,Next,etc are subclasses of Computer. (Not a great way to do things, but I think it gets the point across) I guess exactly what a factory method is is a matter of how you look at it. But design patterns exist to aid in creating reusable code. And with this in mind, a factory method which returns objects that can't possibly be determined at compile time makes for more reusable code. I'm almost certain that Microsoft's Visual Studio makes extensive use of the FactoryMethod in its drag-and-drop dialog constructor. Decisions about what components to create have to be made dynamically as the user drops them onto the dialogue.

Well, that's my two bits on that. -- Myke

Don't be so hard on yourself, Myke. I think your example is precisely the way a FactoryMethod should work. There are times when you need to make a run-time, data driven decision on which subclass to create. Sometimes I have found that data received from the outside world does not match the class hierarchies we have defined. A FactoryMethod provides this mapping. -- WayneMack


Sounds like you are referring to the Abstract Factory pattern, WayneMack and Myke. At least to the extent of my knowledge of the subject, when using the Factory Method objects should be created of just one class, and the Abstract Factory provides the polymorphism that is suggested in the above Computer example.

Although it might not seem so interesting to create instances of the same class by defining a separate method (Factory Method) for it, there lies a good set of motivations for it. Take for instance the Flyweight pattern, where you need to circulate your objects of a certain class. There is no way (at least one conforming to good design principles) to do this in the constructor. You need the separate method for object creation. That's where the Factory Method kicks in. -- mindcode


The defined methods create1, create2 and create3 are not Factory Methods. Factory Method is directly related to the polymorphism, it’s provides facility to redefine the method (Creating Factory of method) in further hierarchy of classes. Abstract Factory and Factory Method many times work together. One is concentrated on creating the Factory of Classes another on factory of particular method. Here I modify your example; maybe it is helpful to you.

    //Abstract Factory: Define the Abstract Class to make factory of related Classes
    Class EmailAddress?
    {
      //Create three Methods
      EmailAddress? create(String address) =0;

//Some other Methods //Method1()=0;

}

//Creating Concrete Factory of Class: Here I am implementing Abstract Factory Class EmailAddressSMTP: public EmailAddress? { //Creating Concrete Factory of Method: Here I am implementing Factory Method //Define Method “Create” EmailAddress? create(String address) { //Any one from create1, create2 and create3 can be called by putting some validation logic. }

//Define Other needed Methods Particular this class EmailAddress? create1(String address); EmailAddress? create2(String address); EmailAddress? create3(String address);

}

//Creating another Concrete Factory of Class

Class EmailAddressUUCP: public EmailAddress? { //Creating Concrete Factory of Method: Here I am implementing Factory Method //Define Method “Create” vEmailAddress create(String address) { //Any one from create1, create2 and create3 can be called by putting some validation logic. }

//Define Other needed Methods Particular this class EmailAddress? create1(String address); EmailAddress? create2(String address); EmailAddress? create3(String address);

}
Please let me know if you have some comments. softprofessional@yahoo.co.in

Akash


Joshua Bloch uses the term "static factory method" in item 1 of his Effective Java book. Common names are valueOf() for type conversions and getInstance() in general (particularly for singletons). However, this is different from the FactoryMethodPattern, and different from the examples at the top of this page. I would say that the term "factory method" is more general than the FactoryMethodPattern.


The word "factory" should be avoided outside of the GangOfFour FactoryMethodPattern. Many developers throw around the word "factory" because it sounds "Patternish"... even if they're just referring to a static method wrapping the constructor (which could just be called a static create method). "Factory" implies a constructor that can return different types - in the case of a parameterized constructor that returns type based on parameter, a FactoryMethodPattern, or in the case of constructor polymorphism, an AbstractFactoryPattern.


Well, I'm not too surprised. This entire page is dedicated to arguing over the definition of "FactoryMethod", and "What is or isn't a factory". Unlike the estimable GangOfFour, I prefer to describe things as simply as possible, rather than in crypto-pseudo-scientific bunkum. If my definition isn't quite accurate, it gets at the practical matter better. What is a factory? Definition: A factory is a wrapper around 'new'. Now, that's harmless enough and in extremely rare cases it may prove useful. Here's the problem: YouArentGonnaNeedIt. Not once...not ONCE have I ever said this or anything similar: "Oh, boys, we're SCREWED. We should have used a factory but we didn't. Oh, crap. We instantiate this sucker in 10 different places!!! Without a factory to help us swap in new implementations we're done for! What will we do? Might as well cancel the project." I've never had that happen, or anything of the same genre, and I don't expect to. And if that situation comes up, great. We've just discovered a need for a factory: Then is the time to create it. Not before. Not before, dammit.

Why am I saying all this? Because I've been appalled...appalled...by the amount of time "Senior software architects" spend dinking around with diagrams of all the factories a system will have. And talk! Oh, my god, I can still hear people talking about how damn important it is to get the factories *just right*. In the real world, a "factory" is a big important building where work gets done. So clueless people associate hard work with the word "factory". Don't be fooled. I'd like a different term. InstantiationWrapper?, maybe.

I'm not a "senior software architect", but I've found considerable use for Factory procedures - both at the boundaries of library implementations (where I wish to hide implementation to avoid accidental or otherwise unnecessary coupling) and when implementing interpreters that return a number of different implementation objects with the same interface based upon the arguments (e.g. "if the header-bytes of the packet match pattern XYZ, create an instance of ABC" - there might be an arbitrarily large number of these rules, possibly created dynamically using cloned prototypes). It seems to me that, in the latter case at least, the "factory" is a rather important and useful object where real decisions are being made - deciding how to interpret packets, and producing objects that allow ready access to the message stored in the packet. This is true even if you don't ever bother swapping it out for a different Factory object because you don't ever have a different communications context (where the same packet-headers might mean different things).

Your seat-of-the-pants notion that a FactoryMethod is "a wrapper around 'new'" is correct, but it's also a horrible definition... no better than saying "Definition: a dog is an animal". There are a great many wrappers around 'new' that aren't considered FactoryMethods. Do you often write code that doesn't wrap around 'new', returning 'new' objects or values, be they on the stack or heap? Given your emphasis on pragmatism, I expect you don't care much for actually being correct; however, if you really wanted to be 'pragmatic', you'd just shut up and let people who actually care about correctness duke this one out. I'm here more because I'm irritated with your attitude than I am concerned about what means 'FactoryMethod', but I do imagine that the word-phrase would be better defined by its purpose and its usage than by its implementation.

As far as YAGNI goes: you're right. You don't need to understand or intentionally utilize FactoryMethod or Factory... or any pattern, really. Good patterns are merely useful to understand and utilize, and that's all they'll ever need to be.


EditText of this page (last edited November 13, 2014) or FindPage with title or text search