Abstract Factory Pattern - CoffeeScript Design Patterns

Posted on

Here’s the Abstract Factory pattern. It’s useful when you need to create groups of things but you don’t want to specify each of them one by one. It has the added benefit of localizing your dependencies which is nice. I like this pattern because it lets me be more lazy. If you like to do things the hard way and you don’t want your code to be maintainable, you shouldn’t use this pattern.

# Declares an interface for a type of product object.  
class AbstractProductA  
  constructor: (arg) ->  
    console.log arg

class AbstractProductB  
constructor: (arg) ->  
console.log arg

# * Defines a product object to be created by the corresponding
#   concrete factory.
# * Implements the AbstractProduct interface.

class ConcreteProductA1 extends AbstractProductA  
class ConcreteProductA2 extends AbstractProductA  
class ConcreteProductB1 extends AbstractProductB  
class ConcreteProductB2 extends AbstractProductB

# Declares an interface for operations that create abstract
# product objects.

class AbstractFactory # (WidgetFactory)  
  createProductA: () ->  
  createProductB: () ->

# Implements the operations to create concrete product objects.

class ConcreteFactory1 extends AbstractFactory  
  createProductA: () ->  
    new ConcreteProductA1 "ConcreteProductA1"  
  createProductB: () ->  
    new ConcreteProductB1 "ConcreteProductB1"

# Implements the operations to create concrete product objects.

class ConcreteFactory2 extends AbstractFactory  
  createProductA: () ->  
    new ConcreteProductA2 "ConcreteProductA2"  
  createProductB: () ->  
    new ConcreteProductB2 "ConcreteProductB2"

# Uses only interfaces declared by AbstractFactory and
# AbstractProduct classes.

class Client  
  constructor: (factory) ->  
    @abstractProductA = factory.createProductA()  
    @abstractProductB = factory.createProductB()  


factory1 = new ConcreteFactory1()  
client1 = new Client factory1

factory2 = new ConcreteFactory2()  
client2 = new Client factory2