go 面向对象编程方法

go 中没有类,但是可以使用结构体、指针和闭包特性实现面向对象编程。

实例:

package main

import "fmt"

type Test struct {
	z float32
}

func NewTest(z float32) *Test {
	return &Test{z:z}
}

func (t *Test) SetZ(z float32)  {
	t.z = z
}

func (t *Test) GetZ() float32 {
	return t.z
}

// 定义结构体,结构体变量就相当于类变量
type TestClass struct {
	x int   // 封装,变量首字母小写,只能使用 SetX 或者 GetX 访问;如果首字母大写则可以外部访问
	y string
	*Test	// 继承
}

// 实现构造函数
func NewTestClass(x int, y string, z float32) *TestClass {
	return &TestClass{
		x:    x,
		y:    y,
		Test: NewTest(z),
	}
}

// 闭包实现成员方法
func (t *TestClass) SetX(x int) {
	t.x = x
}

func (t *TestClass) GetX() int  {
	return t.x
}

func (t *TestClass) SetY(y string) {
	t.y = y
}

func (t *TestClass) GetY() string  {
	return t.y
}

func main(){
	testClass := NewTestClass(0, "first", 0.0)

	fmt.Println(testClass.GetX())
	fmt.Println(testClass.GetY())
	fmt.Println(testClass.GetZ())

	testClass.SetX(1)
	testClass.SetY("go")
	testClass.SetZ(1.2)

	fmt.Println(testClass.GetX())
	fmt.Println(testClass.GetY())
	fmt.Println(testClass.GetZ())
}

总的来说,go 使用这种方法实现了面向对象三大特性中的封装和继承,多态就需要使用接口 interface 了。

实例:

package main

import "fmt"

type AnimalIF interface {
	Sleep()
	Age() int
	Type() string
}

type Animal struct {
	MaxAge int
}

type Cat struct {
	Animal Animal
}

func (c *Cat) Sleep() {
	fmt.Println("Cat need sleep")
}
func (c *Cat) Age() int {
	return c.Animal.MaxAge
}
func (c *Cat) Type() string {
	return "Cat"
}

type Dog struct {
	Animal Animal
}

func (d *Dog) Sleep() {
	fmt.Println("Dog need sleep")
}
func (d *Dog) Age() int {
	return d.Animal.MaxAge
}
func (d *Dog) Type() string {
	return "Dog"
}

func Factory(name string) AnimalIF {
	switch name {
	case "dog":
		return &Dog{Animal{MaxAge: 20}}
	case "cat":
		return &Cat{Animal{MaxAge: 10}}
	default:
		panic("No such animal")
	}
}

func main() {
	animal := Factory("dog")
	animal.Sleep()
	fmt.Printf("%s max age is: %d", animal.Type(), animal.Age())
}

猜你喜欢

转载自www.cnblogs.com/leffss/p/12551368.html