Hatena::Groupvim

[script][designpattern]Singleton

[script][designpattern]Singleton

Singleton

let s:Singleton = {}

function! s:Singleton.initialize()
  let self.count = 0
  return extend({}, self)
endfunction

function! s:Singleton.getInstance()
  if !exists('s:instance')
    let s:instance = s:Singleton.initialize()
  endif
  return s:instance
endfunction

function! s:Singleton.countUp()
  let self.count = self.count + 1
  return self.count
endfunction

let obj1 = s:Singleton.getInstance()
echo obj1.countUp()
let obj2 = s:Singleton.getInstance()
echo obj2.countUp()
echo obj1.countUp()
echo obj2.countUp()

実行結果

1
2
3
4