发送信息----策略模式

发送信息----策略模式

  • 发送信息

发送信息

发送信息到手机、邮箱等,可扩展

package main

import (
	"errors"
	"fmt"
)



type PushContext struct {
	Phone, Email, Message string
	Tage                  int
}

type PaymentStrategy interface {
	Push(*PushContext)
}

func NewPush(phone, email, message string, tage int, strategy PaymentStrategy) *Push {
	return &Push{
		Content: &PushContext{
			Phone:   phone,
			Email:   email,
			Message: message,
			Tage:    tage,
		},
		Strategy: strategy,
	}
}

type Push struct {
	Content  *PushContext
	Strategy PaymentStrategy
}

func (p *Push) Push() {
	p.Strategy.Push(p.Content)
}

//==================================================================================================================

type PushPhone struct {
	Content string
	Phone   string
}

func (p *PushPhone) Push(ctx *PushContext) {
	fmt.Printf("发送到手机:Send Message %s to phone %s by cash\n", ctx.Message, ctx.Phone)
}

type PushEmail struct {
	Content string
	Email   string
}

func (p *PushEmail) Push(ctx *PushContext) {
	fmt.Printf("发送到邮箱:Send Message %s to Email %s by cash\n", ctx.Message, ctx.Email)
}

var sendMethod = make(map[string]PaymentStrategy)
func init() {
	sendMethod["PushPhone"] = &PushPhone{}
	sendMethod["PushEmail"] = &PushEmail{}
}

func main() {
	pushMessage("13301161111", "", "这是发给手机的短信", "PushPhone", 1)
	pushMessage("", "[email protected]", "这是发给邮箱的邮件", "PushEmail", 1)

}

func pushMessage(phone, email, message, sty string, tage int) error {
	//查询信息,得到phone、email、发送标识等
	strategy, ok := sendMethod[sty]
	if !ok {
		return errors.New("没有这个策略")
	}
	payment := NewPush(phone, email, message, tage, strategy)
	payment.Push()

	return nil
}

你可能感兴趣的:(golang,策略模式)