Hatena::Groupvim

[script][designpattern]TemplateMethod

[script][designpattern]TemplateMethod

TemplateMethod

let Display = {}

" initialize
function! Display.initialize()
  return extend({}, self)
endfunction

function! Display.display(str)
  let self.messages = []
  let self.length = strlen(a:str)
  call self.open()
  call self.write(a:str)
  call self.close()
  echo self.join()
endfunction

let CharDisplay = {}
" inheritance
call extend(CharDisplay, Display)

function! CharDisplay.open()
  call add(self.messages, '<<')
endfunction

function! CharDisplay.close()
  call add(self.messages, '>>')
endfunction

function! CharDisplay.write(str)
  call add(self.messages, a:str)
endfunction

function! CharDisplay.join()
  return join(self.messages, '')
endfunction

let StringDisplay = {}
" inheritance
call extend(StringDisplay, Display)

function! StringDisplay.open()
  let str = '+'
  while strlen(str) < self.length + 3
    let str .= '-'
  endwhile
  let str .= '+'
  call add(self.messages, str)
endfunction

function! StringDisplay.close()
  call self.open()
endfunction

function! StringDisplay.write(str)
  call add(self.messages, '| ' . a:str . ' |')
endfunction

function! StringDisplay.join()
  return join(self.messages, "\n")
endfunction

let char_diaplay = CharDisplay.initialize()
let string_diaplay = StringDisplay.initialize()
call char_diaplay.display('foo')
call string_diaplay.display('foo')
call char_diaplay.display('barbaz')
call string_diaplay.display('barbaz')

実行結果

<<foo>>
+-----+
| foo |
+-----+
<<barbaz>>
+--------+
| barbaz |
+--------+