直接代码:
ackage main import "fmt" //现在有教室和宿舍,教室两扇们,窗户高两米, 宿舍一扇门,窗户高一米 type Room struct { doorNum int windowHeight int } func (r *Room) showRoomInfo() { fmt.Println("door num:", r.doorNum, "door windowHeight:", r.windowHeight) } type RoomBuilder interface { build() *Room } func BuildRoom(builder RoomBuilder) *Room { return builder.build() } type Cla***oomBuilder struct { } func (*Cla***oomBuilder) build() *Room { return &Room{2, 2} } type DormitoryBuilder struct { } func (*DormitoryBuilder) build() *Room { return &Room{1, 1} } func main() { room := BuildRoom(&Cla***oomBuilder{}) room.showRoomInfo() room = BuildRoom(&DormitoryBuilder{}) room.showRoomInfo() //同理我们需要一个客厅一个门没有窗户,就可以写一个客厅的builder //此处例子很简单,而实际中build函数可能处理很复杂的事,通过builder模式可以把具体的 //实例与创建过程分开,如此容易扩展与替换创建过程 } github长期更新: https://github.com/fanux/gopatterns
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/195896.html