结构型 门面模式

为什么需要门面模式

做过建筑行业的同学可能会知道,门面就是幕墙,一般是建筑的最后一步,就是美化。在程序设计上面,这种设计模式主要用于简化接口,减少调包侠的选择范围。一个经典的例子就是银行系统如果想开放转账功能给开发者,这个接口只需要指定transfer(your_id, recipient_id, amount)。这个接口本身就是门面设计,因为可能封装了底层的账户记录,转账记录,到账通知等一系列操作。

实现

就是用一个struct去尽量封装底层api。

go.mod

module facade

go 1.13

facade.go

package facade

import "fmt"

type WalletFacade struct {
	account      Account
	notification Notification
}

func NewWalletFacade() *WalletFacade {
	return &WalletFacade{
		account:      &BankAccount{},
		notification: &EmailNotification{},
	}
}

func (w *WalletFacade) AddMoney(amount int) string {
	w.account.AddMoney(amount)
	return w.notification.Notify(amount)
}

type Account interface {
	AddMoney(int)
}

type BankAccount struct {
	saving int
}

func (b *BankAccount) AddMoney(amount int) {
	b.saving += amount
}

type Notification interface {
	Notify(int) string
}

type EmailNotification struct{}

func (e *EmailNotification) Notify(amount int) string {
	return fmt.Sprintf("Email: %d has been saved to your account", amount)
}

facade_test.go

package facade_test

import (
	"facade"
	"testing"
)

func TestFacade(t *testing.T) {
	wallet := facade.NewWalletFacade()
	if wallet.AddMoney(10) != "Email: 10 has been saved to your account" {
		t.Fatal("Expecting", wallet.AddMoney(10))
	}
}

执行: go test facade -v

Previous
Next