This commit is contained in:
crusader 2017-11-27 18:57:43 +09:00
parent 2122e939e8
commit f3b7cb5bdf

View File

@ -2,66 +2,75 @@ package context
import "sync"
type AttributeManager interface {
Init()
SetAttribute(key string, value interface{})
GetAttribute(key string) (value interface{})
RemoveAttribute(key string)
type Attributes interface {
initialize()
Set(key string, value interface{})
Get(key string) (value interface{})
Remove(key string)
Contains(key string) (exist bool)
Destroy()
}
type AttributeManagers struct {
Parent AttributeManager
attributes map[string]interface{}
func NewAttributes(parent Attributes) Attributes {
am := &attributes{
Parent: parent,
}
am.initialize()
return am
}
type attributes struct {
Parent Attributes
values map[string]interface{}
mtx sync.RWMutex
}
func (am *AttributeManagers) Init() {
func (am *attributes) initialize() {
if nil != am.Parent {
am.Parent.Init()
am.Parent.initialize()
}
if nil == am.attributes {
if nil == am.values {
am.Destroy()
}
am.attributes = make(map[string]interface{})
am.values = make(map[string]interface{})
}
func (am *AttributeManagers) SetAttribute(key string, value interface{}) {
func (am *attributes) Set(key string, value interface{}) {
am.checkInitialized()
am.mtx.Lock()
defer am.mtx.Unlock()
am.attributes[key] = value
am.values[key] = value
}
func (am *AttributeManagers) GetAttribute(key string) (value interface{}) {
func (am *attributes) Get(key string) (value interface{}) {
am.checkInitialized()
am.mtx.RLock()
defer am.mtx.RUnlock()
if _, ok := am.attributes[key]; ok {
return am.attributes[key]
if _, ok := am.values[key]; ok {
return am.values[key]
}
if nil == am.Parent {
return nil
}
return am.Parent.GetAttribute(key)
return am.Parent.Get(key)
}
func (am *AttributeManagers) RemoveAttribute(key string) {
func (am *attributes) Remove(key string) {
am.checkInitialized()
am.mtx.Lock()
defer am.mtx.Unlock()
if _, ok := am.attributes[key]; ok {
delete(am.attributes, key)
if _, ok := am.values[key]; ok {
delete(am.values, key)
return
}
@ -69,16 +78,16 @@ func (am *AttributeManagers) RemoveAttribute(key string) {
return
}
am.Parent.RemoveAttribute(key)
am.Parent.Remove(key)
}
func (am *AttributeManagers) Contains(key string) (exist bool) {
func (am *attributes) Contains(key string) (exist bool) {
am.checkInitialized()
am.mtx.RLock()
defer am.mtx.RUnlock()
if _, ok := am.attributes[key]; ok {
if _, ok := am.values[key]; ok {
return true
}
@ -88,9 +97,9 @@ func (am *AttributeManagers) Contains(key string) (exist bool) {
return am.Parent.Contains(key)
}
func (am *AttributeManagers) Destroy() {
if nil != am.attributes {
am.attributes = nil
func (am *attributes) Destroy() {
if nil != am.values {
am.values = nil
}
if nil != am.Parent {
@ -98,8 +107,8 @@ func (am *AttributeManagers) Destroy() {
}
}
func (am *AttributeManagers) checkInitialized() {
if nil == am.attributes {
func (am *attributes) checkInitialized() {
if nil == am.values {
panic("Attribute Manager: must be initialized")
}
}