golang学习笔记-小试OOP

先上图
golang学习笔记-小试OOP_第1张图片


简单的工厂模式

package main

import (
	"fmt"
	"go_code/test/model"
)

func main() {
	driver := model.Driver{
		Name: "zhangsan",
		Age:  20,
	}
	car := model.NewCar("benze", 120)
	fmt.Println("car --->", car)
	fmt.Println("driver --->", driver)
	driver.Drive(car)
}

package model

import "fmt"

//car car
type car struct {
	Name  string
	Speed int
}

//Driver driver
type Driver struct {
	Name string
	Age  byte
}

//Drive drive
func (driver *Driver) Drive(c car) {
	fmt.Printf("driver %v is driving %v \n", driver.Name, c.Name)
}

//NewCar 简单的工厂模式
func NewCar(name string, speed int) car {
	return car{
		Name:  name,
		Speed: speed,
	}
}


通过实现sort接口实现简单的排序

package main

import (
	"fmt"
	"math/rand"
	"sort"
)

//Monster 自定义对象
type Monster struct {
	Name string
	Age  int
}

//MonsterSlice Monsterdui应的切片类型
type MonsterSlice []Monster

//sort排序需实现sort.Sort方法参数中的接口
func (ms MonsterSlice) Len() int {
	return len(ms)
}
func (ms MonsterSlice) Less(i, j int) bool {
	return ms[i].Age < ms[j].Age
}
func (ms MonsterSlice) Swap(i, j int) {
	// tmp := ms[i]
	// ms[i] = ms[j]
	// ms[j] = tmp
	//简写方式
	ms[i], ms[j] = ms[j], ms[i]
}

func main() {
	var ms MonsterSlice
	for i := 0; i < 5; i++ {
		ms = append(ms, Monster{
			Name: fmt.Sprintf("monster-%d", rand.Intn(100)),
			Age:  rand.Intn(1000),
		})
	}
	for _, v := range ms {
		fmt.Println(v)
	}
	//
	sort.Sort(ms)
	fmt.Println("------------")
	for _, v := range ms {
		fmt.Println(v)
	}

}

空接口

package main

import (
	"fmt"
)

type Monster struct {
	Name  string
	Skill string
	Age   int
}

//ShowType interface{}
func ShowType(i interface{}) {
	fmt.Printf(" type is %T \n", i)
}

func main() {
	//空接口 interface{}
	//因interface{}未定义任何方法,故golang中任何类型都是空接口的实现

	ShowType(2)
	monster := Monster{
		Name:  "monster",
		Skill: "kill",
		Age:   290,
	}
	ShowType(monster)
}

你可能感兴趣的:(golang,golang,go)