乐趣区

关于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()
    }
}
退出移动版