2

I am currently studying design patterns from the book (which, although I didn't try anything else, I find excellent) Head First Design Patterns.

I'm confused about two concepts: The Factory Method, and the Factory Method Design Pattern.

I was trying to understand what each one means, and I came to some conclusion. I'd like to know if my definitions are exact.


The Factory Method is a method that is meant to do one thing: Create an object of a specific supertype and return it. It may or may not take a parameter, and may or may not 'decide' using if statements what kind of concrete object to create.

For example, this is a factory method:

public Hat createHat(String hatColor){

    Hat hat;

    if (hatColor.equals("red")) hat = new RedHat();
    else if (hatColor.equals("blue")) hat = new BlueHat();
    else if (hatColor.equals("green")) hat = new GreenHat();
    else hat = new DefaultHat();

    return hat;

}

The Factory Method Design Pattern is named after the Factory Method.

This pattern provides a specific way to encapsulate object creation from the client.

It works like so: The pattern is a system of two classes, the Creator and the ConcreteCreator. The Creator is an abstract class, and the ConcreteCreator is a subclass of that class.

The job of the ConcreteCreator - create an object and return it using a factory method. It only has to contain this one method.

The job of the Creator - manipulate and use the object received from it's subclass, the ConcreteCreator, and usually return it to the client.

It is done like so:

The Creator contains an abstract method, it's signature something like SupertypeObject createObject(). Whenever it needs an object of type SupertypeObject, it calls createObject().

Thing is, createObject() is as I said abstract. It's the ConcreteCreator's job to implement this method.

This way, the implementation of createObject() is hidden from the Creator. It doesn't know what concrete object it gets, but it knows for sure that it's of type SypertypeObject.

This way, a client can use the Creator object to create objects of some supertype, but the concrete objects created will depend on the subclass. Thus declaring ShoeFactory factory = new CaliforniaStyleShoesFactory(), will make the factory produce california style shoes, while ShoeFactory factory = new NYStyleShoesFactory() will make the factory produce NY style shoes. Since the implementation of creating the concrete objects depends on the ConcreteCreator.

Code to demonstrate:

Class Client(){

    public static void main(String[] args){

        ShoeFactory factory;
        Shoe shoe;

        factory = new NYStyleShoeFactory();
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A NY style shoe".

        // ShoeFactory's makeShoe() invokes createShoe() in the subclass, receives a Shoe
        // (doesn't know the concrete type of the Shoe. Depends on the subclass) and
        // does manipulations on it.
        // Returns the Shoe to the client.

        factory = new CaliforniaStyleShoeFactory():
        shoe = factory.makeShoe();
        System.out.println(shoe.getDescription()); // "A California style shoe".

}

}

Is my understanding of the two concepts accurate? Thanks

  • 2
    What you are calling the "Factory Method design pattern" sounds more like an Abstract Factory pattern to me. What you're calling the Factory Method IS the design pattern. See programmers.stackexchange.com/questions/81838/… – pdr Mar 21 '14 at 11:30
  • @pdr What I called a Factory Method is a method. How can one method be a pattern? – Aviv Cohn Mar 21 '14 at 11:33
  • 1
    Check the link in @pdr's comment, it explains the Factory Method and Abstract Factory patterns beautifully. – yannis Mar 21 '14 at 11:44
  • @Prog - where does it say that a pattern should be anything more than a method? You could also look at this SO question for a very elaborate answer on the subject: stackoverflow.com/questions/4209791/… – Uri Agassi Mar 21 '14 at 11:45
  • 1
    @Prog: Yes. I would add that the Factory Method pattern is very specifically a method that selects which concrete implementation of a common supertype to return based on whatever information you give it. That's an important distinction from simply "a method that creates an object and returns it", which could easily include a constructor or the build part of the Builder pattern, neither of which are a Factory Method. – pdr Mar 21 '14 at 12:48
2

Yes, you are right.

The pattern is called like that because it describes a known, well accepted solution using a factory method.

The pattern could have been named "XXXX". That doesn't matter.

Regarding @pdr's comment about what you describe being really an "Abstract Factory", the following images clarify the difference, Factory Method is exactly what you describe:

enter image description here

enter image description here

The images are taken from this PDF taken from this site. It was maded by a software engineer by the name of Jason McDonald.

  • Thanks for your comment. Started to think I got everything wrong ;) . One question: The concrete factory classes involved in the Abstract Factory pattern, also utilize factory methods, right? (Not the pattern, but the method). – Aviv Cohn Mar 21 '14 at 16:35
  • 1
    Also, I have another confusion: It seems to me the AbstractFactory class in Abstract Factory is equivalent to the Creator class in Factory Method, and that the ConcreteFactory class in Abstract Factory is equivalent to the ConcreteCreator class in Factory Method - but with one difference - the classes in Abstract Factory utilize a number of factory methods (the method, not the pattern) to create different objects that are somehow related, while the classes in Factory Method utilize only one factory method to create one object. It seems to me that's the only difference. Am I wrong? – Aviv Cohn Mar 21 '14 at 16:39
  • Yes, createProductA() and createProductB() are factory methods. Think of abstract factories as as composite creators that creates related things to form a whole, for example a pizza AF could have the following methods: createTopping(), createCrust(), createDough(). Concrete implementations of that methods behave differently (but have the same name) to create Hawaiian pizza, Margherita piazza, Capricciosa pizza etc, pizzas with thick crust, thin crust, more or less yeast, etc. – Tulains Córdova Mar 21 '14 at 18:52
  • 1
    I understand why it would make sense to have one factory class with several methods to create related products, like with your pizza example. But what I don't understand is this: Other than the fact that the concrete factories of the Abstract Factory pattern each have a number of methods to create related products, while the concrete factories of the Factory Method pattern have only one method to create a product - What are the differences between the two patterns? Apart from the fact that one creates families of products, and the other a single product, I see no difference. – Aviv Cohn Mar 21 '14 at 19:03
  • @Prog It seems to me that the "only" difference is than AF's product is a complex, composite one. It also seems to me that it's a big difference. – Tulains Córdova Mar 21 '14 at 19:14
0

You said something in a comment that bears highlighting and explanation.

How can one method be a pattern?

While most design patterns are templates of classes or objects and how they all relate to each other, that's really only true of object oriented design patterns. The topic of design patterns has applicability far beyond that, and there are some design patterns, like factory or interface, that apply very well to implementations using a single method or function.

For example, we can use both in a simple functional JavaScript program. Let's say we have something like what follows, to call an ActiveX object our company uses on an Intranet.

var oNeat = new ActiveXObject("OurCompany.NeatThing");
oNeat.DoStuff();

Seems simple, except we can wrap both lines above in a pair of respective pattens.

function GetNeatThing() {
  return new ActiveXObject("OurCompany.NeatThing");
}

function DoStuff(onWhat) {
  if(onWhat && onWhat.DoStuff) {
    onWhat.DoStuff();
  }
}

and then our call becomes simply:

var oNeat = GetNeatThing();
DoStuff(oNeat);

While this doesn't get us a lot by itself, we do get significantly better modularity. If we move the GetNeatThing and DoStuff functions into their own js file, and use them instead of the hard-coded references, we wind up with all of the benefits of having a Factory and an Interface.

(Specifically, we could change the progID of our NeatThing, or even move it away from ActiveX to something like a web server. And we could even change how it works, by re-naming the atrocious "DoStuff" method to something more descriptive, while not breaking existing code.)

  • What you describe, according to the book I'm reading, is called Simple Factory and is considered a language idiom, not a design pattern (have no idea why) – Aviv Cohn Mar 21 '14 at 16:42
  • (Actually, not Simple Factory, but Static Factory) – Aviv Cohn Mar 21 '14 at 17:54
  • You're reading a book about Object Oriented Design Patterns. Nothing wrong with leaving off the first two words, since "OODP" is kind of a mouthful even as an abbreviation. But design patterns aren't just applicable to OOP-based langauegs like C# or Java, nor does using their ideas require forcing OOP features onto a functional langauge like JavaScript. – DougM Mar 21 '14 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.