1.一个简单的实现
package main
import (
"errors"
"fmt"
)
type IDatabase interface{
Connect() error // 接口不指定参数,返回error
Disconnect() error
}
type Mysql struct{
DBname string
isConnect bool
}
// 实现IDatabase接口
func (mysql *Mysql)Connect()error{
fmt.Println("mysql name",mysql.DBname)
mysql.isConnect = true
if mysql.isConnect{
fmt.Println("mysql Connect!")
return nil
}
return errors.New("Connect failure!")
}
func (mysql *Mysql)Disconnect()error{
mysql.isConnect = false
if !mysql.isConnect{
fmt.Println("mysql DisConnect!")
return nil
}
return errors.New("Disconnect failure!")
}
type Redis struct{
DBname string
isConnect bool
}
func (redis *Redis)Connect()error{
fmt.Println("redis name:",redis.DBname)
redis.isConnect = true
if redis.isConnect{
fmt.Println("redis Connect!")
return nil
}
return errors.New("Connect failure!")
}
func (redis *Redis)Disconnect()error{
redis .isConnect = false
if !redis .isConnect{
fmt.Println("redis DisConnect!")
return nil
}
return errors.New("Disconnect failure!")
}
func HandleDB(db IDatabase){
//fmt.Println(db.DBname)
db.Connect()
db.Disconnect()
}
func main(){
//面向对象编程
mysql :=&Mysql{
DBname:"mysql",
isConnect:false,
}
redis:=Redis{
DBname:"Redis",
isConnect:false,
}
// 传给结构的参数必须是 引用
HandleDB(mysql)
HandleDB(&redis)
}