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

随性施展

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()
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理