Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active December 15, 2015 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/5222599 to your computer and use it in GitHub Desktop.
Save joyrexus/5222599 to your computer and use it in GitHub Desktop.
Little factory example.

Factory Pattern

Trevor Burnham's example.

class Enterprise 
constructor: (@captain) ->
    @name = @constructor.name
    
class Voyager
constructor: (@captain) ->
    @name = @constructor.name
    
StarshipMaker = (captain) ->
  switch captain
    when "Kirk", "Picard", "Archer"
      new Enterprise(captain)
    when "Janeway"
      new Voyager(captain)
    else  
      throw new Error("Unknown starship captain!")

    
{ok} = require "assert"
    
ship = StarshipMaker "Kirk"
ok ship.name is "Enterprise"
    
ship = StarshipMaker "Janeway"
ok ship.name is "Voyager"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment