package main
import("fmt")type Father struct{
name string
level int}func(*Father)Eat(){
fmt.Println("我是父类的 eat")}func(*Father)Food(){
fmt.Println("我是父类的 food")}type Son struct{
Father
work string}func(*Son)Eat(){
fmt.Println("我是子类的 eat")}func(*Son)Rice(){
fmt.Println("我是子类的 rice")}funcmain(){
f := Father{"张三",1}
f.Eat()// 我是父类的 eat
f.Food()// 我是父类的 food
s := Son{f,"美食家"}
s.Eat()//我是子类的 eat
s.Rice()//我是子类的 rice}
多态
package main
import("fmt")// 定义一个动物的接口type Animal interface{Sleep()GetName()stringGetColor()string}// 定义一个结构体 猫type Cat struct{
name string}// 定义一个结构体 狗type Dog struct{
name string}func(*Dog)Sleep(){
fmt.Println("这只狗在睡觉。。。。。。")}func(this *Dog)GetName()string{return this.name
}func(this *Dog)GetColor()string{return"黑色"}func(*Cat)Sleep(){
fmt.Println("这只猫在睡觉。。。。。。")}func(this *Cat)GetName()string{return this.name
}func(this *Cat)GetColor()string{return"百色"}funcShowAnimal(animal Animal){
animal.Sleep()
fmt.Println("color: ", animal.GetColor())
fmt.Println("name: ", animal.GetName())}funcmain(){
c := Cat{"小白"}
d := Dog{"小黑"}ShowAnimal(&c)ShowAnimal(&d)}
例子
package main
import"fmt"type Builder interface{Build()}type Director struct{
builder Builder
}func(d *Director)Construct(){
d.builder.Build()}funcNewDirector(builder Builder) Director {return Director{builder:builder}}type ConcreteBuilder struct{
built bool}func(b *ConcreteBuilder)Build(){
fmt.Println("我被调用了。。。。")
b.built =true}funcmain(){
cb := ConcreteBuilder{false}
d :=NewDirector(&cb)
d.Construct()println("built is ", cb.built)/*
我被调用了。。。。
true
*/}