finish build pattern

This commit is contained in:
Edward 2020-04-27 12:49:49 +08:00
parent 0a8d87c6ee
commit ade6f11884
2 changed files with 42 additions and 25 deletions

View File

@ -3,13 +3,11 @@ package builder
//ICar 汽车,我们要造车了
//ICar 车具有以下能力
type ICar interface {
Start()
Stop()
Speed() int
Brand() string
}
//ICarBuilder 用来造车
//ICarBuilder 一辆需要具有的部件
type ICarBuilder interface {
Wheel(wheel int) ICarBuilder
Engine(engine string) ICarBuilder
@ -20,10 +18,20 @@ type ICarBuilder interface {
//CarProto 车的原型
type CarProto struct {
Wheel int
Engine string
MaxSpeed int
Brand string
Wheel int
Engine string
MaxSpeed int
BrandName string
}
//Speed 最大车速
func (c *CarProto) Speed() int {
return c.MaxSpeed
}
//Brand 车品牌
func (c *CarProto) Brand() string {
return c.BrandName
}
//CarStudio 打算通过成立造车实验室进行造车
@ -44,20 +52,31 @@ func (c *CarStudio) Wheel(wheel int) ICarBuilder {
// Engine of car
func (c *CarStudio) Engine(engine string) ICarBuilder {
c.prototype.Engine = engine
return c
}
// Speed of car
func (c *CarStudio) Speed(max int) ICarBuilder {
c.prototype.MaxSpeed = max
return c
}
// Brand of car
func (c *CarStudio) Brand(brand string) ICarBuilder {
c.prototype.BrandName = brand
return c
}
// Build return a car
func (c *CarStudio) Build() ICar {
return c.prototype
car := &CarProto{
Wheel: c.prototype.Wheel,
Engine: c.prototype.Engine,
MaxSpeed: c.prototype.MaxSpeed,
BrandName: c.prototype.BrandName,
}
return car
}

View File

@ -1,23 +1,21 @@
package builder
import "testing"
import (
"fmt"
"testing"
)
func TestBuilder1(t *testing.T) {
builder := &Builder1{}
director := NewDirector(builder)
director.Construct()
res := builder.GetResult()
if res != "123" {
t.Fatalf("Builder1 fail expect 123 acture %s", res)
func TestBuilderCar(t *testing.T) {
builder := NewCarStudio()
builder.Brand("sky").Speed(120).Engine("audi")
car := builder.Build()
if car.Speed() != 120 {
t.Fatalf("Builder1 fail expect 120 ,but get %d", car.Speed())
}
if car.Brand() != "sky" {
t.Fatalf("Builder1 fail expect sky ,but get %s", car.Brand())
}
}
func TestBuilder2(t *testing.T) {
builder := &Builder2{}
director := NewDirector(builder)
director.Construct()
res := builder.GetResult()
if res != 6 {
t.Fatalf("Builder2 fail expect 6 acture %d", res)
}
fmt.Println(car.Speed())
fmt.Println(car.Brand())
}