forked from go/golangs_learn
viviman
4 years ago
2 changed files with 92 additions and 0 deletions
@ -0,0 +1,52 @@ |
|||
|
|||
```go |
|||
package abstract_factory |
|||
|
|||
import "fmt" |
|||
|
|||
type Lunch interface { |
|||
Cook() |
|||
} |
|||
|
|||
type Rise struct { |
|||
} |
|||
|
|||
func (r *Rise) Cook() { |
|||
fmt.Println("这是 测试1111。") |
|||
} |
|||
|
|||
type Tomato struct { |
|||
} |
|||
|
|||
func (t *Tomato) Cook() { |
|||
fmt.Println("这是 测试22222。") |
|||
} |
|||
|
|||
type LunchFactory interface { |
|||
CreateFood() Lunch |
|||
CreateVegetable() Lunch |
|||
} |
|||
|
|||
type SimpleLunchFactory struct { |
|||
} |
|||
|
|||
func NewSimpleLunchFactory() LunchFactory { |
|||
return &SimpleLunchFactory{} |
|||
} |
|||
|
|||
func (s *SimpleLunchFactory) CreateFood() Lunch { |
|||
return &Rise{} |
|||
} |
|||
|
|||
func (s *SimpleLunchFactory) CreateVegetable() Lunch { |
|||
return &Tomato{} |
|||
} |
|||
|
|||
``` |
|||
* 实际抽象工厂是对工程的工厂函数的再次接口抽象 |
|||
|
|||
* `type Lunch interface { Cook() }` 声明接口,声明`type Rise struct {}` 和 `type Tomato struct {}` 结构体,通过结构体声明接口函数,使得实现接口,从而实现多态。 |
|||
|
|||
* `type LunchFactory interface { CreateFood() Lunch; CreateVegetable() Lunch }` 声明一个接口,接口中存在不同函数,用于返回不同对象,是对 原 *工厂模式* 升级,使 |
|||
|
|||
* 通过工厂函数,通过调用不同的接口函数,调用不同接口实现,完成(接口)多态调用。而工厂函数返回实际对象,从而使用实际对象,调用接口具体实现。 |
@ -0,0 +1,40 @@ |
|||
|
|||
```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 {}` 结构体,通过结构体声明接口函数,使得实现接口,从而实现多态。 |
|||
|
|||
* 通过工厂函数,通过不同参数,调用不同接口实现,完成(接口)多态调用。而工厂函数返回实际对象,从而使用实际对象,调用接口具体实现。 |
Loading…
Reference in new issue