【设计模式】2、工厂方法模式

在这里插入图片描述

文章目录


当你在编写代码的过程中, 如果无法预知对象确切类别及其依赖关系时, 可使用工厂方法。

工厂方法将创建产品的代码与实际使用产品的代码分离, 从而能在不影响其他代码的情况下扩展产品创建部分代码。

例如, 如果需要向应用中添加一种新产品, 你只需要开发新的创建者子类, 然后重写其工厂方法即可。

示例如下:

package entities

import (
	"fmt"
	"time"
)

// thing has ID, it appears at Time() and Addr()
type thing interface {
    
    
	Time() time.Time
	Addr() string
	ID() string
}

type ThingType string
const (
	ThingTypeRoad = "road"
	ThingTypeShip = "non_oil_pay"
)

type createThingFunc func(tm time.Time, addr, id string) thing

var createThingFuncs = map[ThingType]createThingFunc{
    
    
	ThingTypeInsideVehiclesIndex: newInsideVehiclesIndex,
}

func createThing(thingType ThingType) (createThingFunc, error) {
    
    
	f, ok := createThingFuncs[thingType]
	if !ok {
    
    
		return nil, fmt.Errorf("unsupport thingType: %v", thingType)
	}
	return f, nil
}

func newRoadThing(tm time.Time, addr, id string) thing {
    
    
	return &RoadThing{
    
    
		Ts:        time.Now().UnixMilli(),
		Addr:      addr,
		ID: 	   id,
	}
}

func newShipThing(tm time.Time, addr, id string) thing {
    
    
	return &ShipThing{
    
    
		Ts:        time.Now().UnixMilli(),
		Addr:      addr,
		ID: 	   id,
	}
}

参考
go 实现

猜你喜欢

转载自blog.csdn.net/jiaoyangwm/article/details/131805996
今日推荐