重构享元模式示例,统一服装接口类型,增强代码一致性和可读性

This commit is contained in:
2026-01-02 17:26:52 +08:00
parent 4589debb92
commit 232b926a97
3 changed files with 33 additions and 16 deletions
+11 -6
View File
@@ -7,6 +7,11 @@ import "fmt"
汤宝宝开了一家服装租赁店,好多客人来店里租衣服~
*/
// 享元抽象类
type ClothingInterface interface {
Show()
}
// 享元对象 - 服装
type Clothing struct {
style string
@@ -20,16 +25,16 @@ func (c *Clothing) Show() {
// 享元工厂 - 服装店
type ClothingFactory struct {
clothingPool map[string]*Clothing
clothingPool map[string]ClothingInterface
}
func NewClothingFactory() *ClothingFactory {
return &ClothingFactory{
clothingPool: make(map[string]*Clothing),
clothingPool: make(map[string]ClothingInterface),
}
}
func (f *ClothingFactory) GetClothing(style, size, color string) *Clothing {
func (f *ClothingFactory) GetClothing(style, size, color string) ClothingInterface {
key := style + "-" + size + "-" + color
if clothing, exists := f.clothingPool[key]; exists {
return clothing
@@ -50,17 +55,17 @@ func (f *ClothingFactory) ShowStock() {
// 客人
type Customer struct {
name string
clothing []*Clothing
clothing []ClothingInterface
}
func NewCustomer(name string) *Customer {
return &Customer{
name: name,
clothing: []*Clothing{},
clothing: []ClothingInterface{},
}
}
func (c *Customer) RentClothing(clothing *Clothing) {
func (c *Customer) RentClothing(clothing ClothingInterface) {
fmt.Printf("%s 租了一件服装: ", c.name)
clothing.Show()
c.clothing = append(c.clothing, clothing)