Factory Method Pattern - CoffeeScript Design Patterns

By on

Okay, say an API is shitting out a bunch of products, each of which has a type. You have a bazillion classes for each of those products, but you don’t want to check each one; you just want to get an instance and move on without totally trashing your API class with product logic. Here’s where the Factory Method Pattern comes in handy. Party on Wayne.

[code lang=“coffee”]

Defines the interface of objects the factory method creates.

class Product

  1. Implements the Product interface.

class ConcreteProduct1 extends Product
class ConcreteProduct2 extends Product

  1. * Declares the factory method, which returns an object of type
  2. Product. Creator may also define a default implementation of
  3. the factory method that returns a default ConcreteProduct
  4. object.
  5. * May call the factory method to create a Product object.

class Creator
factoryMethod: () ->
operation: () ->
product = @factoryMethod()

  1. Overrides the factory method to return an instance of a
  2. ConcreteProduct.

class ConcreteCreator extends Creator
factoryMethod: (id) ->
switch id
when id is 1 then return new ConcreteProduct1() when id is 2 then return new ConcreteProduct2()
[/code]

Usage:

[code lang=“coffee”] class Client
@run: () ->
creator = new ConcreteCreator()
console.log creator.factoryMethod 1
console.log creator.factoryMethod 2
console.log creator.factoryMethod 3
[/code]