关于golang:设计模式的GO实现

10次阅读

共计 784 个字符,预计需要花费 2 分钟才能阅读完成。

随性施展

abstract factory pattern

type IProduct interface {show()
}

type ProductEntity struct {

}

func (product *ProductEntity) show(){fmt.Println("product entity")
}

type IFactory interface {createProduct()(product *ProductEntity)
}

type Factory struct {

}

func (factory *Factory) createProduct() (product *ProductEntity) {product = new(ProductEntity)
    return product
}

func main() {factory := new (Factory)
    factory.createProduct().show()
}

observer pattern

type Customer interface {update()
}

type CustomerEntity struct {

}

func (*CustomerEntity) update() {fmt.Println("message accepted")
}

type Producer struct {customers []Customer
}

func (p *Producer) addCustomer(entity *CustomerEntity) {p.customers = append(p.customers, entity)
}

func (p Producer) deleteCustomer(entity *CustomerEntity) {// TODO}

func (p *Producer) notify() {
    for _, customer := range p.customers {customer.update()
    }
}
正文完
 0