golang基础
协程池实现
import "sync"
type Woker interface {
Work()
}
type Pool struct {
work chan Worker
wg sync.WaitGroup
}
func NewPool(maxRoutine int) *Pool {
p := Pool{
work: make(chan Worker)
}
p.wg.Add(maxRoutine)
for i:=0;i<maxRoutine;++i {
go func(){
for v := range work {
v.Work()
}
p.wg.Done()
}()
}
return &p
}
//提交工作到池子
func (p *Pool) Run(w Worker) {
p.work <- w
}
//关闭池子
func (p *Pool) Close() {
close(p.work)
p.wg.Wait()
}
go类似多态实现
package main
import "fmt"
type AnimalIF interface {
Sleep()
Age() int
Type() string
}
type Animal struct {
MaxAge int
}
/*=======================================================*/
type Cat struct {
Animal Animal
}
func (this *Cat) Sleep() {
fmt.Println("Cat need sleep")
}
func (this *Cat) Age() int {
return this.Animal.MaxAge
}
func (this *Cat) Type() string {
return "Cat"
}
/*=======================================================*/
type Dog struct {
Animal Animal
}
func (this *Dog) Sleep() {
fmt.Println("Dog need sleep")
}
func (this *Dog) Age() int {
return this.Animal.MaxAge
}
func (this *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())
}
panic和err的区别
处理错误并且在函数发生错误的地方给用户返回错误信息:照这样处理就算真的出了问题,你的程序也能继续运行并且通知给用户。
panic and recover是用来处理真正的异常(无法预测的错误)而不是普通的错误。
当发生像数组下标越界或类型断言失败这样的运行错误时,Go运行时会触发运行时panic,伴随着程序的崩溃抛出一个runtime.Error接口类型的值。这个错误值有个RuntimeError()方法用于区别普通错误。
go语言实现单例模式
双重检验枷锁
type Singleton struct{
}
var ins *Singleton
var mutex sync.Mutex
func GetIns() *Singleton{
if ins == nil {
mutex.Lock()
if ins == nil {
ins = &Singleton{}
}
mutex.Unlock()
}
return ins
}
sync.Once实现
type Singleton struct{}
var ins *Singleton
var once sync.Once
func GetIns() *Singleton {
once.Do(func() {
ins = &Singleton{}
})
return ins
}
go实现简单工厂
package main
import (
"fmt"
)
type Op interface {
getName() string
}
type A struct {
}
type B struct {
}
type Factory struct {
}
func (a *A) getName() string {
return "A"
}
func (b *B) getName() string {
return "B"
}
func (f *Factory) create(name string) Op {
switch name {
case `a`:
return new(A)
case `b`:
return new(B)
default:
panic(`name not exists`)
}
return nil
}
25、26号面试题知识来源https://blog.csdn.net/littleflypig/article/details/98628692