工厂模式-golang

此篇中主要是工厂模式的练习,具体可以看菜鸟教程(http://www.runoob.com/design-pattern/factory-pattern.html)


package main

import (
   "fmt"
   "strings"
)

func main() {
   s := Shape(Rectangle{})
   s.draw()
   s = Shape(Circle{})
   s.draw()
}

//构建图形绘画工厂
func ShapeFactory(arg string) Shape {
   if arg == "" {
      return nil
   }
   if strings.ToUpper(arg) == "RECTANGLE" {
      return Rectangle{}
   }else if strings.ToUpper(arg) == "CIRCLE" {
      return Circle{}
   }
   return nil
}

//图形绘画接口
type Shape interface {
   draw()
}

//矩形绘画实现
type Rectangle struct {

}

func (r Rectangle ) draw()  {
   fmt.Println("Rectangle draw")
}

//圆形绘画实现
type Circle struct {

}

func (r Circle ) draw()  {
   fmt.Println("Circle draw")
}

发布了48 篇原创文章 · 获赞 17 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/aixinaxc/article/details/79314797
今日推荐