forked from go/golangs_learn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
808 B
40 lines
808 B
4 years ago
|
|
||
|
```go
|
||
|
package factory
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
)
|
||
|
|
||
|
type Restaurant interface {
|
||
|
GetFood()
|
||
|
}
|
||
|
|
||
|
type Aa struct {
|
||
|
}
|
||
|
|
||
|
type Bb struct {
|
||
|
}
|
||
|
|
||
|
func (a *Aa) GetFood() {
|
||
|
fmt.Println("Aa ... 测试工厂生产, ", &a)
|
||
|
}
|
||
|
|
||
|
func (b *Bb) GetFood() {
|
||
|
fmt.Println("Bb ... 测试工厂生产, ", &b)
|
||
|
}
|
||
|
|
||
|
func NewRestaurant(name string) Restaurant {
|
||
|
switch name {
|
||
|
case "Aa":
|
||
|
return &Aa{}
|
||
|
case "Bb":
|
||
|
return &Bb{}
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
```
|
||
|
|
||
|
* `type Restaurant interface { GetFood() }` 声明接口,声明`type Aa struct {}` 和 `type Bb struct {}` 结构体,通过结构体声明接口函数,使得实现接口,从而实现多态。
|
||
|
|
||
|
* 通过工厂函数,通过不同参数,调用不同接口实现,完成(接口)多态调用。而工厂函数返回实际对象,从而使用实际对象,调用接口具体实现。
|