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.
Defines the interface of objects the factory method creates.
- Implements the Product interface.
class ConcreteProduct1 extends Product
class ConcreteProduct2 extends Product
- * Declares the factory method, which returns an object of type
- Product. Creator may also define a default implementation of
- the factory method that returns a default ConcreteProduct
- * May call the factory method to create a Product object.
factoryMethod: () ->
operation: () ->
product = @factoryMethod()
- Overrides the factory method to return an instance of a
class ConcreteCreator extends Creator
factoryMethod: (id) ->
when id is 1 then return new ConcreteProduct1() when id is 2 then return new ConcreteProduct2()
[code lang=“coffee”] class Client
@run: () ->
creator = new ConcreteCreator()
console.log creator.factoryMethod 1
console.log creator.factoryMethod 2
console.log creator.factoryMethod 3