首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go设计模式之简单工厂

go设计模式之简单工厂

原创
作者头像
暮雨
修改2018-11-20 10:33:15
4490
修改2018-11-20 10:33:15
举报
文章被收录于专栏:云端漫步云端漫步

简单工厂是设计模式中最简单的一创建类型模式,通过一个手机的例子,来展示该模式的使用。

先来看下类图的实现

接口:Phone interface

实例:IPhone, XiaoMI, huawei

方法:showBrand()

实现代码如下:

package main

import "fmt"

// 手机类型枚举
type Brand int

const (
	Hawei Brand = 0
	Apple Brand = 1
	XM    Brand = 2
)

type Phone interface {
	ShowBrand()
}

// iphone
type IPhone struct {
}

func (p *IPhone) ShowBrand() {
  fmt.Println("我是苹果手机")
}

// 华为
type HPhone struct {
}

func (p *HPhone) ShowBrand() {
	fmt.Println("我是华为手机")
}

// 小米
type XPhone struct {
}

func (p *XPhone) ShowBrand() {
	fmt.Println("我是华为手机")
}

func NewPhone(brand Brand) Phone {
	switch brand {
	case Hawei:
		return &HPhone{}
	case Apple:
		return &IPhone{}
	case XM:
		return &XPhone{}
	default:
		return nil
	}
}

func main() {
	var phone Phone

	// 华为手机
	phone = NewPhone(Hawei)
	phone.ShowBrand()

	// 小米手机
	phone = NewPhone(XM)
	phone.ShowBrand()

	// 苹果手机
	phone = NewPhone(Apple)
	phone.ShowBrand()
}

此处使用了go语言的枚举,来定义手机的型号

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档