接口实现OCP设计原则
OCP(Open-Closed Principle)——开闭原则
对扩展是开放的,对修改是关闭的
package mainimport "fmt"type Pet interface {eat()sleep()}type Dog struct {}type Cat struct {}// Dog 实现 Pet 接口func (dog *Dog) eat() {fmt.Println("dog eat...")}func (dog *Dog) sleep() {fmt.Println("dog sleep...")}// Cat 实现 Pet 接口func (cat *Cat) eat() {fmt.Println("cat eat...")}func (cat *Cat) sleep() {fmt.Println("cat sleep...")}type Person struct {}// pet 既可以传递Dog也可以传递Catfunc (per *Person) care(pet Pet) {pet.eat()pet.sleep()}func main() {dog := Dog{}cat := Cat{}person := Person{}person.care(&dog)person.care(&cat)}
模拟OOP思想
继承
通过结构体嵌套实现继承
package mainimport "fmt"type Animal struct {name stringage int}func (a Animal) eat() {fmt.Println("eat...")}func (a Animal) sleep() {fmt.Println("sleep...")}type Dog struct {Animalcolor string}type Cat struct {Animalb string}func main() {dog := Dog{Animal{name:"花花",age:2},"黑色",}dog.eat()dog.sleep()fmt.Printf("dog.color: %v\n", dog.color)fmt.Printf("dog.age: %v\n", dog.age)cat := Cat{Animal{name:"嘿嘿", age:3},"bbb",}cat.eat()cat.sleep()fmt.Printf("cat: %v\n", cat)}

