Tuesday, January 27, 2015

Design pattern - Factory method pattern


What is a factory method pattern?

A factory method pattern is a constructor of objects. Basically, it defines an interface for creating an object, but let subclasses decide which class to instantiate.

If you are still having a hard time understanding this method pattern, just think of this. Factory design pattern is very similar to the real factories such as toy manufacturer where they produce toys. Of course they have their machines to do the job over and over again with a lesser risk of defects. And these machines are similar to your generator class. That's it.

Time to reflect

Imagine that you are in a factory where people create stuffs manually. How do you feel about it?

When to use factory pattern?

• generate objects of the same kind with common set of behaviour
• a class that defer instantiation to subclasses
• localise specific object to return

Below is the illustrated factory pattern in UML class diagram.



Sample code in Objective-C language


MyProduct.h

/* My product is the kind of component that we will return */
@interface MyProduct : NSObject
/* Product that will be returned */

@end

ConcreteComponent.h and ConcreteComponent.m

@interface ConcreteComponent : MyProduct
@end

@implementation ConcreteComponent
/* Implement me */
@end

AbstractFactory.h

@interface AbstractFactory : NSObject
  - (MyProduct*) generateComponent;
@end

ConcreteFactory.h and ConcreteFactory.m

@interface ConcreteFactory : AbstractFactory
  @property (nonatomic, strong) MyProduct* product;
  - (MyProduct*) generateComponent;
@end

@implementation ConcreteFactory
  + (MyProduct*) generateComponent
  {
    /* You can add properties if you want */
    return [ConcreteComponent new];
  }
@end

Main method

- (void) viewDidLoad
{
  [super viewDidLoad];
  
  AbstractFactory* factory = [ConcreteFactory new];
  id component = [factory generateComponent];
}


Factory method is one of the commonly used pattern in software development. I hope you can use them effectively.