Factory Method

Definition: The factory method encapsulates object creation by letting subclasses decide what objects to create. Simply defining a class that is a factory isn't a real example of this design pattern. It is only an example of this design pattern if it's an interface that can defer instantiation to subclasses. It is unclear why it is important for the factory method to be part of an interface.

Usage: Use factory methods to create objects when you're not sure exactly which object you will be creating. You can pass the different factories around to determine which type of object will be created dynamically.

Example

interface ButtonFactory {
	createButton()
}

class RoundButtonFactory {
	createButton()
}

class SquareButtonFactory {
	createButton()
}

This sort of code is useful for making code more general, though round and square buttons don't necessarily need to be created by different factories. The round vs. square difference is just something simple to use for an example. In Lucky's Puzzle Carnival, there was a BoundedButtonFactory that wrapped a BoundedWidget (see Decorator) around each button. This was used for a specific type of button that was wider than it really should have been because the click animation was wide.

Index

Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.