LoginSignup
43
42

More than 5 years have passed since last update.

CoffeeScriptでデザインパターン

Last updated at Posted at 2014-08-27

y-takanoさんが書いたJavaプログラマから見たJavaScriptデザインパターン(導入編)を見て

CoffeeScriptで どう書いてたかな〜と整理しておこうかなと思いました。

そもそも素のJavaScriptでクラスをキチンと書こうと思ったら 僕は発狂する自信があります。

※ リンク先はCoffeeScript公式サイトになってます。

Adapter


class CustomArray

  constructor: (@data)->
    @sorter = DefaultSorter

  setCustomSorter: (@customSorter) ->
    @sorter = customSorter

  sort: ->
    @data.sort @sorter.sort

class DefaultSorter
  sort: (a, b)-> a - b

class RandomSorter
  sort: -> Math.round(Math.random())-.5

Singleton


class Singleton

  class PrivateClass
    constructor: ->

  instance = null

  @getInstance: ->
    instance ?= new PrivateClass

Memento


class Note
  class Memento
    constructor: (@text) ->

  constructor: (@text) ->

  save: (newText)->
    memento = new Memento @text
    @text = newText
    memento

  restore: (memento)->
    @text = memento.text

Observer


class Classroom

  students = []

  addStudent: (student)->
    students.push student

  start: ->
    for student in students
      setTimeout (self, student)->
        student.writeName self.getRandomInt(5, 20), self.done
      , @getRandomInt(0, 20), @, student

  done: (student)->
    console.log "Done", student.name

  getRandomInt: (min, max)->
    Math.floor( Math.random() * (max - min + 1) ) + min


class Student
  constructor: (@name)->

  writeName: (num, done)->
    console.log i, @name for i in [0...num]
    done(@)

FactoryMethod


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

まとめ

とりあえずSingletonだけでも覚えとくといいんじゃないかなと

最初は全部書いてやるぜ!って勢いだったんですけど すみません 疲れました おやすみなさい。

参考

http://qiita.com/y-takano/items/1269f4417dc80d014d39
http://www.techscore.com/tech/DesignPattern/index.html/
http://coffeescriptcookbook.com/chapters/design_patterns/

43
42
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
42