继承
package main
import "fmt"
type People struct {
name string
age int
gender string
}
type Programmer struct {
People
level string
}
func main() {
data := Programmer{People{"why",24, "male"},"P7"}
fmt.Println(data.name, data.gender, data.age, data.level) //why male 24 P7
}
接口规范
package main
import "fmt"
//接口定义方法
type Action interface {
run(color string)
}
//结构体定义people对象
type People struct {
name string
}
//结构体定义animal对象
type Animal struct {
name string
}
//对象(结构体)实现接口定义的方法
func (p *People) run(color string) {
fmt.Printf("%v穿着%v色的衣服在跑步\n", p.name, color)
}
//对象(结构体)实现接口定义的方法
func (a *Animal) run( color string) {
fmt.Printf("%v穿着%v色的衣服在跑步\n",a.name, color)
}
func main() {
//接口不能实例化,所以只能通过对接口的结构体实例化
p := &People{"why"}
a := &Animal{"小狗"}
p.run("紫")
a.run("黄")
}
策略者模式:通过struct和interface实现多态(原理:通过interface实现的方法可以被多个struct实现)
package main
import "fmt"
//定义interface
type Action interface {
canDo()
showPosition()
}
//结构体定义people对象
type People struct {
name string
postion string
}
//不同对象(结构体)实现同一个方法
func (p *People) canDo() {
fmt.Printf("所以%v会做饭\n", p.name)
}
func (p *People) showPosition() {
fmt.Printf("因为%v有%v,", p.name, p.postion)
}
//结构体定义animal对象
type Animal struct {
name string
position string
}
func (a *Animal) canDo() {
fmt.Printf("所以%v会摇尾巴\n", a.name)
}
func (a *Animal) showPosition() {
fmt.Printf("因为%v有%v,", a.name, a.position)
}
func main() {
var action Action
action = &People{"why", "手"}
action.showPosition()
action.canDo()
action = &Animal{"小狗", "尾巴"}
action.showPosition()
action.canDo()
}
单例模式
type singleton struct {}
var instance *singleton
func GetIns() *singleton {
sync.Once.Do( func(){
instance = &singleton{}
})
return instance
}
简单工厂模式:
package main
import (
"fmt"
)
type Factory struct{}
func (*Factory) CreateAnimal(name string) Animal {
switch name {
case "dog":
return new(Cat)
case "cat":
return new(Dog)
default:
return nil
}
}
type Animal interface {
Echo()
}
type Cat struct{}
func (*Cat) Echo() {
fmt.Println("wang wang")
}
type Dog struct{}
func (*Dog) Echo() {
fmt.Println("miao miao")
}
func main() {
factory := Factory{}
cat := factory.CreateAnimal("cat")
dog := factory.CreateAnimal("dog")
cat.Echo()
dog.Echo()
}