Golang設計模式——工廠模式


package fatory

import "fmt"

type Device interface{
   StartDevice()
}

type KeyBoard struct {

}

func (k *KeyBoard) StartDevice(){
   fmt.Println("Keyboard is ready to work!")
}

type Mouse struct {

}

func (m *Mouse) StartDevice(){
   fmt.Println("Mouse is ready to work!")
}

func NewDevice(device string)Device{
   switch device{
   case "k":
      return &KeyBoard{}
   case "m":
      return &Mouse{}
   default:
      return nil
   }

}


測試用例

package fatory

import "testing"

func TestNewDevice(t *testing.T) {
   NewDevice("k").StartDevice()
   NewDevice("m").StartDevice()
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章