GO语言:工厂模式(Factory Method)

14 篇文章 0 订阅
2 篇文章 0 订阅

GO简单工厂

由于 Go 中缺少类和继承等 OOP(面向对象) 特性, 所以无法使用 Go 来实现经典的工厂方法模式。 不过, 我们仍然能实现的基础版本.

场景

一个制作玩具的工厂。

代码结构
为了方便展示 放到了不同的文件中

在这里插入图片描述

Toy.go

定义个玩具的接口 声明共有的方法

package codeInHere

//定义玩具产品接口
type toy interface {
	SetName( name string) //需要个名字
	GetName()  string
	SetUnitPrice(price int)   //定义个单价
	GetUnitPrice()   int
}
ToyAchieve.go

定义实现的结构体 实现玩具接口的方法

package codeInHere

//定义具体产品  在这里实现toy接口
type toyAchieve struct {
 		name string
 		unitPrice int
}
func (t *toyAchieve)GetName() string{
	return t.name
}

func (t *toyAchieve)GetUnitPrice() int{
	return t.unitPrice
}

func (t *toyAchieve)SetUnitPrice( price int) {
	  t.unitPrice = price
}

func (t *toyAchieve)SetName( name string) {
	t.name = name
}
YellowDuck.go

定义具体的产品

package codeInHere

//具体产品玩具 小黄鸭
type yellowDuck struct {
	toyAchieve
}

func newYellowDuck() toy {
	return &yellowDuck{
		toyAchieve{
			unitPrice: 100,
			name:      "小黄鸭"},
	}
}

Transformers.go

定义具体的产品

package codeInHere

type transformers struct {
	toyAchieve
}

func newTransformers() toy {
	return &transformers{toyAchieve{name: "变形金刚", unitPrice: 1000}}
}

ToyFactory.go

创建工厂

package codeInHere

import "fmt"

func 	GetToy(toyType string)(toy ,error){
	if toyType == "yellowDuck"{
		return  newYellowDuck(),nil
	}else if toyType == "transformers"{
		return newTransformers(),nil
	}else {
		return  nil,fmt.Errorf("not have this")
	}
}
main.go
package main
运行
import (
	"designPatterns/FactoryMethod/codeInHere"
	"fmt"
)
func main() {
	yellowDuck,_ := codeInHere.GetToy("yellowDuck")
	transformers,_:=codeInHere.GetToy("transformers")

	fmt.Printf("toyName : %s,toyPrice : %v" ,yellowDuck.GetName(),yellowDuck.GetUnitPrice())
	fmt.Println()
	fmt.Printf("toyName : %s,toyPrice : %v" ,transformers.GetName(),transformers.GetUnitPrice())
}
输出

toyName : 小黄鸭,toyPrice : 100
toyName : 变形金刚,toyPrice : 1000

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值