손 으로 golang 행위 형 디자인 모델 위임 모드
6840 단어 golang 디자인 모드 위임 모드
발단
최근 디자인 모드 복습 담 용 덕 의 < > 본 시리즈 노트 는 골 랑 으로 연습 할 예정 입 니 다.
위임 모드
위임 모델 (Delegate Pattern) 은 위탁 모델 이 라 고도 부른다. 기본 적 인 역할 은 바로 임무 의 호출 과 분 배 를 담당 하 는 특수 한 정적 대리 모델 로 전권 대리 모델 로 이해 할 수 있 지만 대리 모델 은 과정 을 중시 하고 위임 모델 은 결 과 를 중시한다.위임 모드 에는 3 개의 참여 캐릭터 가 있다.(1) 추상 적 인 임무 역할 (ITask): 추상 적 인 인 인 터 페 이 스 를 정의 하 는데 몇 가지 실현 유형 이 있다.(2) 위임 자 역할 (Delegate): 각 구체 적 인 역할 사례 간 에 결정 을 내리 고 구체 적 인 실현 방법 을 판단 하고 호출 하 는 것 을 책임 진다.(3) 구체 적 인 미 션 캐릭터 (Concrete): 미 션 을 제대로 수행 하 는 캐릭터.
장면
설계 하 다.
delegate_pattern_test.go
package behavioral_patterns_test
import (
"fmt"
"learning/gooop/behavioral_patterns/delegate"
"testing"
)
func Test_DelegatePattern(t *testing.T) {
dispatcher := delegate.GlobalMsgDispatcher
vEchoMsg := delegate.NewEchoMsg("msg-1", "this is an echo msg")
response := dispatcher.Handle(vEchoMsg)
fmt.Printf(" echo response: id=%v, cls=%v, content=%v
", response.ID(), response.Class(), response.Content())
vTimeMsg := delegate.NewTimeMsg("msg-2")
response = dispatcher.Handle(vTimeMsg)
fmt.Printf(" time response: id=%v, cls=%v, content=%v
", response.ID(), response.Class(), response.Content())
}
테스트 출력
$ go test -v delegate_pattern_test.go
=== RUN Test_DelegatePattern
tMsgDispatchDelegate.Handle, handler=*delegate.tEchoMsgHandler, id=msg-1, cls=EchoMsg
tEchoMsgHandler.Handle, id=msg-1, cls=EchoMsg
echo response: id=msg-1, cls=EchoMsg, content=this is an echo msg
tMsgDispatchDelegate.Handle, handler=*delegate.tTimeMsgHandler, id=msg-2, cls=TimeMsg
tTimeMsgHandler.Handle, id=msg-2, cls=TimeMsg
time response: id=msg-2, cls=TimeMsg, content=2021-02-05T09:18:45
--- PASS: Test_DelegatePattern (0.00s)
PASS
ok command-line-arguments 0.002s
IMsg.go
정의 메시지 인터페이스
package delegate
type IMsg interface {
ID() string
Class() string
Content() string
}
BaseMsg.go
메시지 의 기본 클래스, IMsg 인터페이스 구현
package delegate
type BaseMsg struct {
sID string
sClass string
sContent string
}
func NewBaseMsg(id string, cls string, content string) *BaseMsg {
return &BaseMsg{
id, cls, content,
}
}
func (me *BaseMsg) ID() string {
return me.sID
}
func (me *BaseMsg) Class() string {
return me.sClass
}
func (me *BaseMsg) Content() string {
return me.sContent
}
EchoMsg.go
돌아 온 다 는 메 시 지 를 PING / PONG 심장 박동 에 사용 합 니 다. Basemsg 에서 계승 합 니 다.
package delegate
type EchoMsg struct {
BaseMsg
}
func NewEchoMsg(id string, content string) *EchoMsg {
return &EchoMsg{
*NewBaseMsg(id, "EchoMsg", content),
}
}
TimeMsg.go
서버 시간 을 가 져 온 다 는 메시지 입 니 다. BaseMsg 에서 계승 합 니 다.
package delegate
import "time"
type TimeMsg struct {
BaseMsg
}
func NewTimeMsg(id string) *TimeMsg {
return &TimeMsg{
*NewBaseMsg(id, "TimeMsg", time.Now().Format("2006-01-02T15:04:05")),
}
}
IMsgHandler.go
메시지 프로세서 인터페이스, 스케줄 러 와 구체 적 인 메시지 프로세서, 모두 이 인 터 페 이 스 를 실현 해 야 합 니 다.
package delegate
type IMsgHandler interface {
Handle(request IMsg) IMsg
}
tMsgDispatchDelegate.go
전역 메시지 스케줄 러 는 모든 클 라 이언 트 메시지 의 통 일 된 입구 입 니 다. 메시지 처리 기 를 등록 하고 유형 에 따라 메 시 지 를 나 누 어 줍 니 다. IMsgHandler 인 터 페 이 스 를 실현 합 니 다.
package delegate
import (
"fmt"
"reflect"
)
type tMsgDispatchDelegate struct {
mSubHandlers map[string]IMsgHandler
}
func (me *tMsgDispatchDelegate) Register(cls string, handler IMsgHandler) {
me.mSubHandlers[cls] = handler
}
func newMsgDispatchDelegate() IMsgHandler {
it := &tMsgDispatchDelegate{
mSubHandlers: make(map[string]IMsgHandler, 16),
}
it.Register("EchoMsg", newEchoMsgHandler())
it.Register("TimeMsg", newTimeMsgHandler())
return it
}
func (me *tMsgDispatchDelegate) Handle(request IMsg) IMsg {
if request == nil {
return nil
}
handler, ok := me.mSubHandlers[request.Class()]
if !ok {
fmt.Printf("tMsgDispatchDelegate.Handle, handler not found: id=%v, cls=%v
", request.ID(), request.Class())
return nil
}
fmt.Printf("tMsgDispatchDelegate.Handle, handler=%v, id=%v, cls=%v
", reflect.TypeOf(handler).String(), request.ID(), request.Class())
return handler.Handle(request)
}
var GlobalMsgDispatcher = newMsgDispatchDelegate()
tEchoMsgHandler.go
EchoMsg 메 시 지 를 전문 적 으로 처리 하 는 프로세서 입 니 다. IMsgHandler 인 터 페 이 스 를 실현 합 니 다.
package delegate
import "fmt"
type tEchoMsgHandler struct {
}
func newEchoMsgHandler() IMsgHandler {
return &tEchoMsgHandler{}
}
func (me *tEchoMsgHandler) Handle(request IMsg) IMsg {
fmt.Printf(" tEchoMsgHandler.Handle, id=%v, cls=%v
", request.ID(), request.Class())
return request
}
tTimeMsgHandler.go
TimeMsg 메 시 지 를 전문 적 으로 처리 하 는 프로세서 로 IMsgHandler 인 터 페 이 스 를 실현 합 니 다.
package delegate
import (
"fmt"
"time"
)
type tTimeMsgHandler struct {
}
func newTimeMsgHandler() IMsgHandler {
return &tTimeMsgHandler{}
}
func (me *tTimeMsgHandler) Handle(request IMsg) IMsg {
fmt.Printf(" tTimeMsgHandler.Handle, id=%v, cls=%v
", request.ID(), request.Class())
timeMsg := request.(*TimeMsg)
timeMsg.sContent = time.Now().Format("2006-01-02T15:04:05")
return timeMsg
}
위임 모드 소결
위임 모델 의 장점 은 임무 위임 을 통 해 대형 임 무 를 세분 화 한 다음 에 이런 하위 임무 의 완성 상황 을 통일 적 으로 관리 함으로써 임무 의 수행 을 실현 하고 임무 수행 의 효율 을 가속 화 할 수 있다.위임 모드 의 단점 임무 위임 방식 은 임무 의 복잡 도 에 따라 달라 져 야 하 며, 임무 가 복잡 한 상황 에서 다 중 위임 이 필요 할 수 있 으 며, 문란 하기 쉽다.(end)