Golang享元模式

242 阅读1分钟

Overview

We usually use the Pool Mode, such as database connection pool, http connection pool, thread pool, etc. The Flyweight Design Pattern is similar to the pool pattern. If the object exists, I will get the object from the pool. If it does not exist, I will create the object and put it into the pool. We can save resources when creating objects.

Pool Mode.jpg

Code

flyweight.go

package designpattern

import "time"

type Flyweight interface {
	Operate() string
}

type PersonFlyweight struct {
	IdNo string
	Name string
}

func (person *PersonFlyweight) Operate() string {
	return person.Name
}

func newPersonFlyweight(IdNo string) *PersonFlyweight {
	println("Wait for 10 seconds to connect to the database and get data")
	time.Sleep(time.Second * 10)
	return &PersonFlyweight{IdNo: IdNo, Name: mockGetPersonNameByIdNo(IdNo)}
}

var mockPersonData = map[string]string{"1": "Nick", "2": "John", "3": "Benjamin", "4": "Martin", "5": "Lisa"}

func mockGetPersonNameByIdNo(idNo string) string {
	if v, ok := mockPersonData[idNo]; ok {
		return v
	} else {
		return "Unknow"
	}
}

var flyweightPool = make(map[string]Flyweight)

func GetFlyweightByFactory(idNo string) Flyweight {
	if v, ok := flyweightPool[idNo]; ok {
		return v
	} else {
		pf := newPersonFlyweight(idNo)
		flyweightPool[idNo] = pf
		return flyweightPool[idNo]
	}
}

flyweight_test.go

package designpattern_test

import (
	designpattern "ptarmigan-golang-design-pattern/src"
	"testing"
)

func TestFlyweight(t *testing.T) {
	nick1 := designpattern.GetFlyweightByFactory("1")
	nick2 := designpattern.GetFlyweightByFactory("1")

	if nick1 != nick2 {
		t.Error("There aren't same person!")
	} else {
		println("Another object is obtained from the Pool rather than created")
	}

	unknow1 := designpattern.GetFlyweightByFactory("7")
	unknow2 := designpattern.GetFlyweightByFactory("8")
	if unknow1 == unknow2 {
		t.Error("There are same Object!")
	} else {
		println("Although both objects are named 'unknown', they were created twice, so they are not the same object")
	}

}

result:

Wait for 10 seconds to connect to the database and get data

Another object is obtained from the Pool rather than created

Wait for 10 seconds to connect to the database and get data

Wait for 10 seconds to connect to the database and get data

Although both objects are named 'unknown', they were created twice, so they are not the same object

PASS