golang设计模式之简单工厂模式

来源:互联网 发布:大数据 维基百科 编辑:程序博客网 时间:2024/06/06 01:52

1. 写在前面

在面向对象的编程语言中(如java,C++)设计模式的概念广为人知, 应用的也非常广泛。设计模式让我们的代码变得灵活起来,具有很强的扩展性。但在与C语言比肩的Go语言中,设计模式的概念并没有十分突出,甚至很少听到。在Go的开发中,借鉴design pattern的理念同样回味无穷我们的开发带来极大的便利。

go-logo

相关源代码demo在Github上,可供参考!

2. 简单工厂模式

类图:

和传统的Java等面向对象语言的继承机制不同,在Go语言中并不提倡使用继承,但是在某些场景下要用到继承的话,可以用下面的方式实现继承关系。

type Animal struct {  Category string}type Dog struct {  Animal  Name string}

简单工厂模式实现起来也比较简单,主要代码如下:

type AnimalFactory struct {}func NewAnimalFactory() *AnimalFactory {    return &AnimalFactory{}}func (this *AnimalFactory) CreateAnimal(name string) Action {    switch name {    case "bird":        return &Bird{}    case "fish":        return &Fish{}    case "dog":        return &Dog{}    default:        panic("error animal type")        return nil    }}