Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript factory method pattern


May 09, 2021 CoffeeScript


Table of contents


Factory method mode

Problem

You don't know what kind of objects you need until you start running.

Solution

Both factory Method mode and selection objects are dynamically generated.

You need to load a file into the editor, but you won't know its format until the user selects the file. A class that uses factory Method mode can provide different parsers depending on the file's extension.

class HTMLParser
    constructor: ->
        @type = "HTML parser"
class MarkdownParser
    constructor: ->
        @type = "Markdown parser"
class JSONParser
    constructor: ->
        @type = "JSON parser"

class ParserFactory
    makeParser: (filename) ->
        matches = filename.match /\.(\w*)$/
        extension = matches[1]
        switch extension
            when "html" then new HTMLParser
            when "htm" then new HTMLParser
            when "markdown" then new MarkdownParser
            when "md" then new MarkdownParser
            when "json" then new JSONParser

factory = new ParserFactory

factory.makeParser("example.html").type # => "HTML parser"

factory.makeParser("example.md").type # => "Markdown parser"

factory.makeParser("example.json").type # => "JSON parser"

Discuss

In this example, you can focus on the parsed content and ignore the format of the detail file. More advanced factory methods, such as searching for the data itself in a version control file, and then returning a more accurate parser (for example, returning an HTML5 parser instead of an HTML v4 parser).