您的位置 首页 golang

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()
}

 


文章来源:智云一二三科技

文章标题:Golang设计模式——工厂模式

文章地址:https://www.zhihuclub.com/179.shtml

关于作者: 智云科技

热门文章

网站地图