1
0
Fork 0
design-patterns/go/flyweight/main.go

108 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import "fmt"
/*
实例:
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
*/
// 享元抽象类
type ClothingInterface interface {
Show()
}
// 享元对象 - 服装
type Clothing struct {
style string
size string
color string
}
func (c *Clothing) Show() {
fmt.Printf("服装款式:%s尺码%s颜色%s\n", c.style, c.size, c.color)
}
// 享元工厂 - 服装店
type ClothingFactory struct {
clothingPool map[string]ClothingInterface
}
func NewClothingFactory() *ClothingFactory {
return &ClothingFactory{
clothingPool: make(map[string]ClothingInterface),
}
}
func (f *ClothingFactory) GetClothing(style, size, color string) ClothingInterface {
key := style + "-" + size + "-" + color
if clothing, exists := f.clothingPool[key]; exists {
return clothing
}
newClothing := &Clothing{style: style, size: size, color: color}
f.clothingPool[key] = newClothing
return newClothing
}
func (f *ClothingFactory) ShowStock() {
fmt.Println("\n服装库存")
for key, clothing := range f.clothingPool {
fmt.Printf("Key: %s -> ", key)
clothing.Show()
}
}
// 客人
type Customer struct {
name string
clothing []ClothingInterface
}
func NewCustomer(name string) *Customer {
return &Customer{
name: name,
clothing: []ClothingInterface{},
}
}
func (c *Customer) RentClothing(clothing ClothingInterface) {
fmt.Printf("%s 租了一件服装: ", c.name)
clothing.Show()
c.clothing = append(c.clothing, clothing)
}
func (c *Customer) ShowClothing() {
fmt.Printf("\n客人%s租赁的服装有\n", c.name)
for _, cloth := range c.clothing {
cloth.Show()
}
}
func main() {
fmt.Println("============= 享元模式 =============")
factory := NewClothingFactory()
// 客人1租衣服
customer1 := NewCustomer("小红")
customer1.RentClothing(factory.GetClothing("连衣裙", "M", "红色"))
customer1.RentClothing(factory.GetClothing("牛仔裤", "L", "蓝色"))
// 客人2租衣服
customer2 := NewCustomer("小明")
customer2.RentClothing(factory.GetClothing("连衣裙", "M", "红色")) // 共享同一件连衣裙
customer2.RentClothing(factory.GetClothing("西裤", "S", "白色"))
fmt.Println()
// 显示租赁情况
customer1.ShowClothing()
customer2.ShowClothing()
// 显示服装库存
factory.ShowStock()
fmt.Println()
fmt.Println("=========== 享元模式结束 ===========")
}