享元模式

享元模式

享元接口

package flyweight

type flyWeight interface{
    setColor(string)
    getShape()string
}

享元角色

package flyweight

type shape struct {
    name string
    color string
}

享元角色圆形

package flyweight

import "fmt"

var circle *Circle

type Circle struct {
	shape
}

func NewCircle() *Circle {
	if circle == nil {
		circle = &Circle{}
		circle.name = "圆形"
	}
	return circle
}

func (c *Circle) setColor(color string) {
	c.color = color
}

func (c *Circle) getShape() string {
	return c.name
}

func (c *Circle) String() string {
	return fmt.Sprintf("形状为:%s,颜色为:%s", c.name, c.color)
}

享元角色长方形

package flyweight

import "fmt"

var rect *Rectangle

type Rectangle struct {
	shape
}

func NewRectangle() *Rectangle {
	if rect == nil {
		rect = &Rectangle{}
		rect.name = "长方形"
	}
	return rect
}

func (r *Rectangle) setColor(color string) {
	r.color = color
}

func (r *Rectangle) getShape() string {
	return r.name
}

func (r *Rectangle) String() string {
	return fmt.Sprintf("形状为:%s,颜色为:%s", r.name, r.color)
}

享元工厂

package flyweight

import "sync"

var (
	factory *FlyWeightFactory
	once    sync.Once
)

type FlyWeightFactory struct {
	hash map[string]flyWeight
}

func NewFactory() *FlyWeightFactory {
	once.Do(func() {
		factory = &FlyWeightFactory{
			hash: make(map[string]flyWeight),
		}
	})
	return factory
}

func (f *FlyWeightFactory) Get(name string) flyWeight {
	if _, ok := f.hash[name]; !ok {
		var sp flyWeight
		switch name {
		case "圆形":
			sp = NewCircle()
			f.hash[name] = sp
		case "长方形":
			sp = NewRectangle()
			f.hash[name] = sp
		}
	}
	return f.hash[name]
}

测试文件

package flyweight

import (
	"fmt"
	"testing"
)

func TestFlyWeight(t *testing.T) {
	fac := NewFactory()
	s1 := fac.Get("长方形")
	s1.setColor("红色")
	fmt.Println(s1)

    s2 := fac.Get("圆形")
    s2.setColor("绿色")
    fmt.Println(s2)
}
posted @ 2022-09-19 09:45  理科土拨鼠  阅读(13)  评论(0)    收藏  举报