factory

package module
v0.0.0-...-c99ef0c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 25, 2016 License: Apache-2.0 Imports: 8 Imported by: 0

README

Factory

A object factory like java's spring bean factory

Features
  1. Dependency Inject
  2. Dynamic create object instance
Usage
Define your model
type Wheel struct {
	ID string
}

type Car struct {
	owner string

	Wheel1 *Wheel
	Wheel2 *Wheel
	Wheel3 *Wheel
	Wheel4 *Wheel
}
Register your model
factory.RegisterModel((*Wheel)(nil), "Michelin")
factory.RegisterModel((*Car)(nil), "Skoda")
Build factory
carFactory := factory.NewClassicFactory(nil)

carFactory.Define("wheel", factory.Prototype, "Michelin", factory.DefOptOfNewObjectFunc(NewWheel))

	err = carFactory.Define("mycar", factory.Prototype, "Skoda",
		factory.DefOptOfNewObjectFunc(NewCar),
		factory.DefOptOfObjectRef("Wheel1", "wheel", factory.Options{"id": "1"}),
		factory.DefOptOfObjectRef("Wheel2", "wheel", factory.Options{"id": "2"}),
		factory.DefOptOfObjectRef("Wheel3", "wheel", factory.Options{"id": "3"}),
		factory.DefOptOfObjectRef("Wheel4", "wheel", factory.Options{"id": "4"}),
	)

The func NewWheel and NewCar is your user-define new func, it should define as

func(opts Options) (v interface{}, err error)

you could get your option from Options

The car depend on wheel, so we use factory.DefOptOfObjectRef for configurate model ref, the first param is filed of Car's name, the Ref object initial order is params order, you also could use factory.DefOptOfRefOrder to define ref object initial order.

Get object
var myCar interface{}
myCar, err = carFactory.GetObject("mycar", factory.Options{"owner": "GoGap"})

if err != nil {
	fmt.Println(err)
	return
}

car := myCar.(*Car)
Example
type Hub struct {
	ID string
}

func NewHub(opts factory.Options) (hub interface{}, err error) {
	h := &Hub{}
	opts.Get("id", &h.ID)
	hub = h
	return
}

type Wheel struct {
	ID string

	Hub *Hub
}

func NewWheel(opts factory.Options) (wheel interface{}, err error) {
	w := &Wheel{}
	opts.Get("id", &w.ID)
	wheel = w
	return
}

func (p *Wheel) Run() {
	fmt.Printf("Wheel Running, ID: %s, HubID: %s\n", p.ID, p.Hub.ID)
}

type Car struct {
	owner string

	Wheel1 *Wheel
	Wheel2 *Wheel
	Wheel3 *Wheel
	Wheel4 *Wheel
}

func (p *Car) Run() {
	p.Wheel1.Run()
	p.Wheel2.Run()
	p.Wheel3.Run()
	p.Wheel4.Run()

	fmt.Printf("%s' Car Running\n", p.owner)
}

func NewCar(opts factory.Options) (car interface{}, err error) {
	c := &Car{}
	opts.Get("owner", &c.owner)
	car = c
	return
}

func init() {
	factory.RegisterModel((*Hub)(nil), "BBS")
	factory.RegisterModel((*Wheel)(nil), "Michelin")
	factory.RegisterModel((*Car)(nil), "Skoda")
}

func main() {

	var err error

	carFactory := factory.NewClassicFactory(nil)

	carFactory.Define("hub", factory.Prototype, "BBS", factory.DefOptOfNewObjectFunc(NewHub))

	carFactory.Define("wheel", factory.Prototype, "Michelin", factory.DefOptOfNewObjectFunc(NewWheel))

	err = carFactory.Define("mycar", factory.Prototype, "Skoda",
		factory.DefOptOfNewObjectFunc(NewCar),
		factory.DefOptOfObjectRef("Wheel1", "wheel", factory.Options{"id": "1"}),
		factory.DefOptOfObjectRef("Wheel2", "wheel", factory.Options{"id": "2"}),
		factory.DefOptOfObjectRef("Wheel3", "wheel", factory.Options{"id": "3"}),
		factory.DefOptOfObjectRef("Wheel4", "wheel", factory.Options{"id": "4"}),
		factory.DefOptOfObjectRef("Wheel1.Hub", "hub", factory.Options{"id": "HUB01"}),
		factory.DefOptOfObjectRef("Wheel2.Hub", "hub", factory.Options{"id": "HUB02"}),
		factory.DefOptOfObjectRef("Wheel3.Hub", "hub", factory.Options{"id": "HUB03"}),
		factory.DefOptOfObjectRef("Wheel4.Hub", "hub", factory.Options{"id": "HUB04"}),
	)

	if err != nil {
		return
	}

	var myCar interface{}
	myCar, err = carFactory.GetObject("mycar", factory.Options{"owner": "GoGap"})

	if err != nil {
		fmt.Println(err)
		return
	}

	car := myCar.(*Car)

	car.Run()
}

Output
> go run main.go
Wheel Running, ID: 1, HubID: HUB01
Wheel Running, ID: 2, HubID: HUB02
Wheel Running, ID: 3, HubID: HUB03
Wheel Running, ID: 4, HubID: HUB04
GoGap' Car Running

Documentation

Index

Constants

View Source
const (
	ErrNamespace = "gogap-factory"
)

Variables

View Source
var (
	ErrEmptyObjectDefinitionName         = errors.TN(ErrNamespace, 1000, "empty object definition name")
	ErrObjectDefinitionAlreadyRegistered = errors.TN(ErrNamespace, 1001, "object definition already registered, name: {{.name}}, type: {{.type}}")
	ErrObjectNotExist                    = errors.TN(ErrNamespace, 1002, "object not exist, name: {{.name}}")
	ErrObjectDefintionNotExist           = errors.TN(ErrNamespace, 1003, "object definition not exist, name: {{.name}}")
	ErrReflectValueNotValid              = errors.TN(ErrNamespace, 1004, "reflect value not valid")
	ErrStructFieldNotExist               = errors.TN(ErrNamespace, 1005, "struct field not exist, field name: {{.name}}")
	ErrObjectMustBeStruct                = errors.TN(ErrNamespace, 1007, "object must be struct, name: {{.name}}")
	ErrCouldNotSetFiledOfNilObject       = errors.TN(ErrNamespace, 1008, "object is nil, could not inject filed value, field: {{.field}}")
	ErrCouldNotSetZeroNumFieldObject     = errors.TN(ErrNamespace, 1009, "file number is zero, could not inject filed value, filed: {{.field}}")
	ErrObjectIsNotStruct                 = errors.TN(ErrNamespace, 1010, "the object must be a struct or ptr to struct")
	ErrRefObjectShouldBePtr              = errors.TN(ErrNamespace, 1011, "ref object should be ptr")
	ErrRefFieldShouldBePtr               = errors.TN(ErrNamespace, 1012, "ref field should be ptr")
	ErrEmptyFieldName                    = errors.TN(ErrNamespace, 1013, "empty field name")
	ErrBadFieldName                      = errors.TN(ErrNamespace, 1014, "bad field name, field name: {{.name}}")
	ErrModelAlreayRegistered             = errors.TN(ErrNamespace, 1015, "model already registered, name: {{.name}}, type: {{.type}}")
	ErrModleAliasAlreadyExist            = errors.TN(ErrNamespace, 1016, "model alias already exist and model name not match, original name: {{.originalName}}, new name: {{.newName}}")
	ErrModelNameIsEmpty                  = errors.TN(ErrNamespace, 1017, "model name is empty")
	ErrModelNotExist                     = errors.TN(ErrNamespace, 1018, "model of {{.name}} not exist")
	ErrRefDefinitionNameIsEmpty          = errors.TN(ErrNamespace, 1019, "ref definition name is empty, def name: {{.name}}")
	ErrFiledAreadyRef                    = errors.TN(ErrNamespace, 1020, "field already ref others definition, original ref defition name: {{.name}}")
	ErrFieldIsZeroValue                  = errors.TN(ErrNamespace, 1021, "filed is zero value, field name: {{.name}}")
	ErrBadRefOrderLength                 = errors.TN(ErrNamespace, 1022, "ref order does not equal definition refs")
	ErrRefOrderContainNonExistRef        = errors.TN(ErrNamespace, 1023, "ref order contain non exist def ref, name: {{.name}}")
)

Functions

func RegisterModel

func RegisterModel(model interface{}, aliases ...string) (err error)

Types

type ClassicFactory

type ClassicFactory struct {
	// contains filtered or unexported fields
}

func (*ClassicFactory) ContainsObject

func (p *ClassicFactory) ContainsObject(name string) bool

func (*ClassicFactory) Define

func (p *ClassicFactory) Define(
	name string,
	scope Scope,
	model string,
	opts ...DefinitionOption) (err error)

func (*ClassicFactory) GetAliases

func (p *ClassicFactory) GetAliases(name string) (aliases []string, err error)

func (*ClassicFactory) GetObject

func (p *ClassicFactory) GetObject(name string, opts ...Options) (obj interface{}, err error)

func (*ClassicFactory) GetType

func (p *ClassicFactory) GetType(name string) (typ reflect.Type)

func (*ClassicFactory) IsPrototype

func (p *ClassicFactory) IsPrototype(name string) bool

func (*ClassicFactory) IsSingleton

func (p *ClassicFactory) IsSingleton(name string) bool

func (*ClassicFactory) IsTypeMatch

func (p *ClassicFactory) IsTypeMatch(name string, typ reflect.Type) bool

type ClassicModelProvider

type ClassicModelProvider struct {
	// contains filtered or unexported fields
}

func (*ClassicModelProvider) Get

func (p *ClassicModelProvider) Get(name string) (typ reflect.Type, exist bool)

func (*ClassicModelProvider) Register

func (p *ClassicModelProvider) Register(model interface{}, aliases ...string) (err error)

type DefinitionOption

type DefinitionOption struct {
	// contains filtered or unexported fields
}

func DefOptOfInitialFunc

func DefOptOfInitialFunc(fnName string) DefinitionOption

func DefOptOfNewObjectFunc

func DefOptOfNewObjectFunc(fn NewObjectFunc) DefinitionOption

func DefOptOfObjectRef

func DefOptOfObjectRef(fieldName string, refDefName string, opts ...Options) DefinitionOption

func DefOptOfRefOrder

func DefOptOfRefOrder(check bool, order ...string) DefinitionOption

type Factory

type Factory interface {
	ContainsObject(name string) bool
	GetAliases(name string) (aliases []string, err error)
	GetObject(name string, opts ...Options) (obj interface{}, err error)
	GetType(name string) (typ reflect.Type)

	IsPrototype(name string) bool
	IsSingleton(name string) bool
	IsTypeMatch(name string, typ reflect.Type) bool

	Define(name string, scope Scope, model string, opts ...DefinitionOption) error
}

func NewClassicFactory

func NewClassicFactory(modelProvider ModelProvider) Factory

type ModelProvider

type ModelProvider interface {
	Register(model interface{}, aliases ...string) (err error)
	Get(name string) (typ reflect.Type, exist bool)
}

func NewClassicModelProvider

func NewClassicModelProvider() ModelProvider

type NewObjectFunc

type NewObjectFunc func(opts Options) (v interface{}, err error)

type ObjectDefinition

type ObjectDefinition struct {
	// contains filtered or unexported fields
}

func (*ObjectDefinition) Aliases

func (p *ObjectDefinition) Aliases() []string

func (*ObjectDefinition) InitialFuncName

func (p *ObjectDefinition) InitialFuncName() string

func (*ObjectDefinition) IsTypeMatch

func (p *ObjectDefinition) IsTypeMatch(typ reflect.Type) bool

func (*ObjectDefinition) Name

func (p *ObjectDefinition) Name() string

func (*ObjectDefinition) NewObjectFunc

func (p *ObjectDefinition) NewObjectFunc() NewObjectFunc

func (*ObjectDefinition) Scope

func (p *ObjectDefinition) Scope() Scope

func (*ObjectDefinition) String

func (p *ObjectDefinition) String() string

func (*ObjectDefinition) Type

func (p *ObjectDefinition) Type() reflect.Type

type ObjectInstance

type ObjectInstance struct {
	// contains filtered or unexported fields
}

func (*ObjectInstance) Definition

func (p *ObjectInstance) Definition() ObjectDefinition

func (*ObjectInstance) Id

func (p *ObjectInstance) Id() string

func (*ObjectInstance) Instance

func (p *ObjectInstance) Instance() interface{}

func (*ObjectInstance) Options

func (p *ObjectInstance) Options() Options

func (*ObjectInstance) String

func (p *ObjectInstance) String() string

type Options

type Options map[string]interface{}

func (Options) Get

func (p Options) Get(name string, v interface{}) (exist bool)

func (Options) ToObject

func (p Options) ToObject(v interface{}) (err error)

type Scope

type Scope int
const (
	Singleton Scope = 0
	Prototype Scope = 1
)

Directories

Path Synopsis
example
car

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL