直接代码:
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 ClassRoomBuilder struct { } func (*ClassRoomBuilder) build() *Room { return &Room{2, 2} } type DormitoryBuilder struct { } func (*DormitoryBuilder) build() *Room { return &Room{1, 1} } func main() { room := BuildRoom(&ClassRoomBuilder{}) room.showRoomInfo() room = BuildRoom(&DormitoryBuilder{}) room.showRoomInfo() //同理我们需要一个客厅一个门没有窗户,就可以写一个客厅的builder //此处例子很简单,而实际中build函数可能处理很复杂的事,通过builder模式可以把具体的 //实例与创建过程分开,如此容易扩展与替换创建过程 }
时间: 2024-11-13 23:09:27