Drkcore

14 01 2012 javascript coffeescript Tweet

CoffeeScriptでObserverパターン

javascriptパターンの7章のサンプルをCoffeeScriptでかきなおしてみた。オリジナルのコードはこれ。

コンソールログを開くと実行されていることがわかる。

ProductName JavaScriptパターン ―優れたアプリケーションのための作法
Stoyan Stefanov
オライリージャパン / 2940円 ( 2011-02-16 )


CoffeeScriptで書きなおしたほうの実行結果。ターミナルで確認できるので楽ですね。

$ coffee pubsub.coffee 
Just read big news today
Just read big news today
Just read big news today
About to fall asleep reading this interesting analysis

コード。デバッグ用にprintSubscribersっていうメソッドを付けた。それからオリジナルコードはmix-inしていたので最初はfor-of文でそのとおりに書いたんだけど、for-of文でtypeof methodするとfunctionじゃなくてstringが返ってくるのが嫌だったので、継承を使って実装してみた。

class Publisher
  constructor: ->
    @subscribers = { any:[] }

  subscribe: (fn, type) ->
    type = type or 'any'
    @subscribers[type] = [] unless @subscribers[type]?
    @subscribers[type].push(fn)

  unsubscribe: (fn, type) -> @visitSubscriers('unsubscribe', fn, type)

  publish: (publication, type) -> @visitSubscriers('publish', publication, type)

  visitSubscriers: (action, arg, type) ->
    pubtype = type or 'any'
    subscribers = @subscribers[pubtype]
    for subscribe,i in @subscribers[pubtype]
      switch action
        when 'publish' then subscribe(arg)
        else @subscribers[pubtype].splice(i,1) if subscribe is arg

  printSubscribers: -> console.log(@subscribers)

class Paper extends Publisher
  daily: => @publish('big news today')
  monthly: => @publish('interesting analysis','monthly')

class Subscriber
  drinkcoffee: (paper) -> console.log('Just read '+ paper)
  sundayPreNap: (paper) -> console.log('About to fall asleep reading this '+ paper)

paper = new Paper
joe = new Subscriber
paper.subscribe(joe.drinkcoffee)
paper.subscribe(joe.sundayPreNap, 'monthly')
#paper.printSubscribers()
paper.daily()
paper.daily()
paper.daily()
paper.monthly()

この本どうなんだろう、一度読んでおくべきなのかな?

ProductName CoffeeScript: Accelerated JavaScript Development
Trevor Burnham
Pragmatic Bookshelf / 2355円 ( 2011-08-03 )


About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021