github.com/polarismesh/polaris@v1.17.8/cache/api/listener.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package api 19 20 // Listener listener for value changes 21 type Listener interface { 22 // OnCreated callback when cache value created 23 OnCreated(value interface{}) 24 // OnUpdated callback when cache value updated 25 OnUpdated(value interface{}) 26 // OnDeleted callback when cache value deleted 27 OnDeleted(value interface{}) 28 // OnBatchCreated callback when cache value created 29 OnBatchCreated(value interface{}) 30 // OnBatchUpdated callback when cache value updated 31 OnBatchUpdated(value interface{}) 32 // OnBatchDeleted callback when cache value deleted 33 OnBatchDeleted(value interface{}) 34 } 35 36 // EventType common event type 37 type EventType int 38 39 const ( 40 // EventCreated value create event 41 EventCreated EventType = iota 42 // EventUpdated value update event 43 EventUpdated 44 // EventDeleted value delete event 45 EventDeleted 46 // EventInstanceReload value instances reload 47 EventInstanceReload 48 // EventPrincipalRemove value principal batch remove 49 EventPrincipalRemove 50 ) 51 52 type ListenerManager struct { 53 listeners []Listener 54 } 55 56 func NewListenerManager() *ListenerManager { 57 return &ListenerManager{ 58 listeners: make([]Listener, 0, 4), 59 } 60 } 61 62 func (l *ListenerManager) Append(listeners ...Listener) { 63 l.listeners = append(l.listeners, listeners...) 64 } 65 66 func (l *ListenerManager) OnEvent(value interface{}, event EventType) { 67 if len(l.listeners) == 0 { 68 return 69 } 70 for _, listener := range l.listeners { 71 switch event { 72 case EventCreated: 73 listener.OnCreated(value) 74 case EventUpdated: 75 listener.OnUpdated(value) 76 case EventDeleted: 77 listener.OnDeleted(value) 78 case EventInstanceReload: 79 listener.OnBatchUpdated(value) 80 case EventPrincipalRemove: 81 listener.OnBatchDeleted(value) 82 } 83 } 84 }