二十、接口的應用示例(便於理解使用場景)

多雲平臺 或者不同平臺的服務器信息 操作相同只是平臺不同 就可以用接口來做

package main

import (
	"fmt"
)

type Cloud interface {
	GetHost() []Host
	Start(id string) error
	Stop(id string) error
	Detil(id string) error
}

type Host struct {
	name string
	ip string
}

type AliCloud struct {
	api string
	key string
	secret string
}

type TenCloud struct {
	api string
	key string
	secret string
}

func NewAliCloud(api,key,secret string) AliCloud {
	return AliCloud{api,key,secret}
}

func NewTenCloud(api,key,secret string) TenCloud {
	return  TenCloud{api,key,secret}
}


func (a AliCloud) GetHost() []Host{
	fmt.Println("Ali GetHost")
	return []Host{}
}

func (a AliCloud) Start(id string) error{
	fmt.Println("Ali Start")
	return  nil
}

func (a AliCloud) Stop(id string) error{
	fmt.Println("Ali Stop")
	return  nil
}

func (a AliCloud) Detil(id string) error{
	fmt.Println("Ali Detil")
	return  nil
}

func (a TenCloud) GetHost() []Host{
	fmt.Println("Ten GetHost")
	return []Host{}
}

func (a TenCloud) Start(id string) error{
	fmt.Println("Ten Start")
	return  nil
}

func (a TenCloud) Stop(id string) error{
	fmt.Println("Ten Stop")
	return  nil
}

func (a TenCloud) Detil(id string) error{
	fmt.Println("Ten Detil")
	return  nil
}

func GetCloud(cloudtype string) Cloud {
	var cloud Cloud
	if cloudtype == "ten" {
		cloud =   NewTenCloud("a","b","c")
	}else if cloudtype == "ali" {
		cloud =   NewAliCloud("a","b","c")
	}else {
		fmt.Println("err")
	}
	return  cloud
}



func main() {
	cloud := GetCloud("ten")
END:
	for {
		//多雲平臺就會用到接口  同種操作針對不同類型 可以複用
		var operator string
		fmt.Print("請輸入操作:")
		fmt.Scan(&operator)
		switch operator {
		case "1":
			cloud.GetHost()
		case "2":
			cloud.Start("1")
		case "3":
			cloud.Stop("2")
		case "4":
			cloud.Detil("3")
		case "5":
			break END
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章