rules

package
v0.0.0-...-ab8afbf Latest Latest
Warning

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

Go to latest
Published: Feb 23, 2021 License: MIT Imports: 4 Imported by: 0

README

factory

工厂模式示例.

rules 是 rule 工厂.

实现介绍

实现了创造者模式, 工厂模式, 以及具体的工厂类(业务相关). 主要分为如下文件

rules.go 定义了Rule服务的接口, 提供统一的调用入口, 各工厂类实现自己具体的业务.

factory.go 定义了工厂模式的接口和Creator的接口.

  • 工厂最核心的职责是Get()接口, 传入工厂类的Name, 返回该工厂类的实例. 其次, 由于业务需要, 在这里我实现了allRuleCreators, 用于获取所有已实现的工厂类Names.
  • Creator: 创造者模式. 每个Rule只要实现Creator, 就可以使用统一的方式创建实例. 使用 Resource 加载所有工厂类需要使用的资源.

demo.go 负责具体的业务实现.

demo_creator.go 负责创建工厂类demo, 并且通过 init() 函数实现了将该工厂类添加到 类集合中, 方便工厂获取所有已实现的工厂类.

如何使用

直接调用 factory 下的 NewFactory() 方法即可创建工厂. 然后可以根据 工厂类name 创建实例.

工厂类使用示例 rule

Documentation

Index

Constants

View Source
const DemoLimit = uint64(30000)
View Source
const DemoRuleName = "demo"

Variables

View Source
var (
	DemoCheckSuccess = &toddler.CheckResult{
		OK:    true,
		Limit: DemoLimit,
	}
	DemoCheckFail = &toddler.CheckResult{
		OK:      false,
		Limit:   DemoLimit,
		Message: "xxxx",
	}
)

Functions

This section is empty.

Types

type DemoCheckRequest

type DemoCheckRequest struct {
	Amount uint64 `gorm:"column:amount" json:"amount"`
}

type DemoCreator

type DemoCreator struct{}

func NewDemoCreator

func NewDemoCreator() *DemoCreator

func (*DemoCreator) Create

func (d *DemoCreator) Create(resource *Resource) IRule

type DemoRule

type DemoRule struct{}

func NewDemoRule

func NewDemoRule() *DemoRule

func (*DemoRule) Check

func (d *DemoRule) Check(params map[string]interface{}) (*toddler.CheckResult, error)

func (*DemoRule) MakeEffective

func (d *DemoRule) MakeEffective() error

type Factory

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

func NewFactory

func NewFactory(resource *Resource) *Factory

func (*Factory) Get

func (f *Factory) Get(name string) (IRule, error)

Get 返回指定的 Rule, 如果找不到, 会返回error

func (*Factory) GetAllRuleCreators

func (f *Factory) GetAllRuleCreators() map[string]IRuleCreator

func (*Factory) GetAllRuleNames

func (f *Factory) GetAllRuleNames() []string

type IRule

type IRule interface {
	// Check 检查是否符合规则
	Check(map[string]interface{}) (*toddler.CheckResult, error)
	MakeEffective() error
}

IRule rule interface

type IRuleCreator

type IRuleCreator interface {
	Create(resource *Resource) IRule
}

IRuleCreator 为工厂提供统一的创建方法

type Resource

type Resource struct{}

Resource 统一资源管理, 存储所有 rule 需要的资源. factory 将 Resource 传入 creator, creator 取其中资源, 交于NewXXRule. 一般而言, 包括 db,cache 等. 此处为了简洁, 暂时略去.

Jump to

Keyboard shortcuts

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