Golang – 常用设计 Factory Pattern
Factory Pattern 就是根据传入的param创建一个相对应的object
- 定义好基础单位和所有单位的样式
const (
CircleType = ShapeType("circle")
TriangleType = ShapeType("triangle")
)
type ShapeType string
2. 定义好Factory和interface标准
type Shape interface {
Draw() string
}
func NewShape(newShapeType ShapeType) Shape {
switch newShapeType {
case CircleType:
return &Circle{}
case TriangleType:
return &Triangle{}
default:
return nil
}
}
3. 定义好Circle Object
type Circle struct {
}
func (this *Circle) Draw() string {
return "this is a circle"
}
4. 定义好Triangle Object
type Triangle struct {
}
func (this *Triangle) Draw() string {
return "this is a triangle"
}
5. 使用案例
func main() {
newShape := NewShape(TriangleType)
if newShape != nil {
checkType := newShape.Draw()
fmt.Println(checkType)
}
}
输出结果:
this is a triangle
Facebook评论