调整接口
This commit is contained in:
@@ -5,23 +5,81 @@ import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
type Email interface {
|
||||
InitEmail(ctx context.Context, opt ...Option) (Email, error)
|
||||
type EmailType string
|
||||
|
||||
type EmailInterface interface {
|
||||
SetOption(ctx context.Context, opt ...Option) (EmailInterface, error) // 初始化
|
||||
GetEmailType() EmailType
|
||||
// Send 发送邮件
|
||||
Send(ctx context.Context, params Message) error
|
||||
}
|
||||
|
||||
type DefaultEmail struct{}
|
||||
type EmailFactoryInterface interface {
|
||||
Register(EmailInterface) // 注册一个接口
|
||||
SetOption(opt ...Option) // 针对已注册的进行初始化
|
||||
GetEmail(EmailType) (EmailInterface, error)
|
||||
UnRegister(EmailType)
|
||||
}
|
||||
|
||||
func (l *DefaultEmail) InitEmail(ctx context.Context, opt ...Option) (Email, error) {
|
||||
return &DefaultEmail{}, errors.New("not implemented")
|
||||
type DefaultEmail struct {
|
||||
Options emailOption
|
||||
EmailType EmailType
|
||||
}
|
||||
|
||||
func NewDefaultEmail() *DefaultEmail {
|
||||
return &DefaultEmail{
|
||||
Options: DefaultOptions(),
|
||||
EmailType: "DefaultEmail",
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DefaultEmail) SetOption(ctx context.Context, opt ...Option) (EmailInterface, error) {
|
||||
// 深复制l并且返回新的
|
||||
newL := *l
|
||||
|
||||
for _, o := range opt {
|
||||
o(&newL.Options)
|
||||
}
|
||||
|
||||
return &newL, nil
|
||||
}
|
||||
|
||||
func (l *DefaultEmail) GetEmailType() EmailType {
|
||||
return l.EmailType
|
||||
}
|
||||
|
||||
func (l *DefaultEmail) Send(ctx context.Context, params Message) error {
|
||||
return errors.New("not implemented")
|
||||
}
|
||||
|
||||
// 初始化一个接口
|
||||
type DefaultEmailFactory struct {
|
||||
Emails map[EmailType]EmailInterface
|
||||
}
|
||||
|
||||
// 实际执行一个接口
|
||||
func NewDefaultEmailFactory() *DefaultEmailFactory {
|
||||
return &DefaultEmailFactory{
|
||||
Emails: make(map[EmailType]EmailInterface),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DefaultEmailFactory) Register(email EmailInterface) {
|
||||
l.Emails[email.GetEmailType()] = email
|
||||
}
|
||||
|
||||
func (l *DefaultEmailFactory) SetOption(opt ...Option) {
|
||||
for _, email := range l.Emails {
|
||||
email.SetOption(context.Background(), opt...)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *DefaultEmailFactory) GetEmail(emailType EmailType) (EmailInterface, error) {
|
||||
email, ok := l.Emails[emailType]
|
||||
if !ok {
|
||||
return nil, errors.New("not implemented")
|
||||
}
|
||||
return email, nil
|
||||
}
|
||||
|
||||
func (l *DefaultEmailFactory) UnRegister(emailType EmailType) {
|
||||
delete(l.Emails, emailType)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user