forked from go/golangs_learn
viviman
4 years ago
8 changed files with 129 additions and 21 deletions
@ -0,0 +1,47 @@ |
|||||
|
package bridage |
||||
|
|
||||
|
import "fmt" |
||||
|
|
||||
|
type Draw interface { |
||||
|
DrawCircle(radius, x, y int) |
||||
|
} |
||||
|
|
||||
|
type RedCircle struct { |
||||
|
} |
||||
|
|
||||
|
func (r *RedCircle) DrawCircle(radius, x, y int) { |
||||
|
fmt.Printf("Red :: radius=%d, x=%d, y=%d\n", radius, x, y) |
||||
|
} |
||||
|
|
||||
|
type YellowCircle struct { |
||||
|
} |
||||
|
|
||||
|
func (r *YellowCircle) DrawCircle(radius, x, y int) { |
||||
|
fmt.Printf("Yellow :: radius=%d, x=%d, y=%d\n", radius, x, y) |
||||
|
} |
||||
|
|
||||
|
type Shape struct { |
||||
|
draw Draw |
||||
|
} |
||||
|
|
||||
|
func (s *Shape) Shape(d Draw) { |
||||
|
s.draw = d |
||||
|
} |
||||
|
|
||||
|
type Circle struct { |
||||
|
shape Shape |
||||
|
x int |
||||
|
y int |
||||
|
radius int |
||||
|
} |
||||
|
|
||||
|
func (c *Circle) Constructor(radius, x, y int, draw Draw) { |
||||
|
c.radius = radius |
||||
|
c.x = x |
||||
|
c.y = y |
||||
|
c.shape.Shape(draw) |
||||
|
} |
||||
|
|
||||
|
func (c *Circle) Draw() { |
||||
|
c.shape.draw.DrawCircle(c.radius, c.x, c.y) |
||||
|
} |
@ -0,0 +1,13 @@ |
|||||
|
package bridage |
||||
|
|
||||
|
import "testing" |
||||
|
|
||||
|
func TestCircle_Draw(t *testing.T) { |
||||
|
red := Circle{} |
||||
|
red.Constructor(100, 100, 10, &RedCircle{}) |
||||
|
red.Draw() |
||||
|
|
||||
|
yellow := Circle{} |
||||
|
yellow.Constructor(200, 200, 20, &YellowCircle{}) |
||||
|
yellow.Draw() |
||||
|
} |
@ -0,0 +1,9 @@ |
|||||
|
|
||||
|
```go |
||||
|
|
||||
|
``` |
||||
|
* 桥接模式 |
||||
|
|
||||
|
* 定义接口并且实现接口,并定义统一结构体,其中一个属性是接口 |
||||
|
|
||||
|
* 调用时,将需要调用对象作为参数传递进行,实现具体对象调用 |
@ -1,6 +1,45 @@ |
|||||
|
|
||||
```go |
```go |
||||
|
package builder |
||||
|
|
||||
|
type Builder interface { |
||||
|
Build() |
||||
|
} |
||||
|
|
||||
|
type Director struct { |
||||
|
build Builder |
||||
|
} |
||||
|
|
||||
|
func NewDirector(b Builder) Director { |
||||
|
return Director{build: b} |
||||
|
} |
||||
|
|
||||
|
func (d *Director) Construct() { |
||||
|
d.build.Build() |
||||
|
} |
||||
|
|
||||
|
type ConcreateBuilder struct { |
||||
|
Built bool |
||||
|
} |
||||
|
|
||||
|
func NewConcreateBuilder() ConcreateBuilder { |
||||
|
return ConcreateBuilder{Built: false} |
||||
|
} |
||||
|
|
||||
|
func (b *ConcreateBuilder) Build() { |
||||
|
b.Built = true |
||||
|
} |
||||
|
|
||||
|
type Product struct { |
||||
|
Built bool |
||||
|
} |
||||
|
|
||||
|
func (b *ConcreateBuilder) GetResult() Product { |
||||
|
return Product{b.Built} |
||||
|
} |
||||
``` |
``` |
||||
* 建造者模式 |
* 建造者模式 |
||||
|
|
||||
* 将整体封装起来,对外仅仅展示一个 调用接口 |
* 封装接口并写实现方法,这是定义的函数,当参数为接口时,入参可以是任何实现接口的实现,并且调用时和作为参数传入时,均会对数据校验。 |
||||
|
|
||||
|
* 在具体接口实现中完成自己想要完成的代码实现,即实现分离。 |
@ -0,0 +1,7 @@ |
|||||
|
|
||||
|
```go |
||||
|
|
||||
|
``` |
||||
|
* 模式 |
||||
|
|
||||
|
* |
Loading…
Reference in new issue