Bootstrap

Golang学习笔记_28——工厂方法模式(实例)

Golang学习笔记_26——通道
Golang学习笔记_27——单例模式
Golang学习笔记_28——工厂方法模式


工厂方法模式(实例)

package factory_method_demo

import "fmt"

// Order 接口,定义订单的基本操作
type Order interface {
	CalculateTotal() float64
	Display()
}

// RegularOrder 是普通订单结构体
type RegularOrder struct {
	Items  []string
	Prices []float64
}

// CalculateTotal 计算普通订单的总价
func (o *RegularOrder) CalculateTotal() float64 {
	var total float64
	for _, price := range o.Prices {
		total += price
	}
	return total
}

// Display 显示普通订单信息
func (o *RegularOrder) Display() {
	fmt.Println("Regular Order:")
	for i, item := range o.Items {
		fmt.Printf("Item %d: %s, Price: %.2f\n", i+1, item, o.Prices[i])
	}
	fmt.Printf("Total Price: %.2f\n", o.CalculateTotal())
}

// PromotionOrder 是促销订单结构体
type PromotionOrder struct {
	Items    []string
	Prices   []float64
	Discount float64
}

// CalculateTotal 计算促销订单的总价
func (o *PromotionOrder) CalculateTotal() float64 {
	var total float64
	for _, price := range o.Prices {
		total += price
	}
	return total * (1 - o.Discount)
}

// Display 显示促销订单信息
func (o *PromotionOrder) Display() {
	fmt.Println("Promotion Order:")
	for i, item := range o.Items {
		fmt.Printf("Item %d: %s, Price: %.2f\n", i+1, item, o.Prices[i])
	}
	fmt.Printf("Total Price (after discount): %.2f\n", o.CalculateTotal())
}

// OrderCreator 是订单创建者接口,包含工厂方法 CreateOrder
type OrderCreator interface {
	CreateOrder(items []string, prices []float64, discount ...float64) Order
}

// RegularOrderCreator 是普通订单创建者结构体
type RegularOrderCreator struct{}

// CreateOrder 创建普通订单
func (roc *RegularOrderCreator) CreateOrder(items []string, prices []float64, discount ...float64) Order {
	return &RegularOrder{
		Items:  items,
		Prices: prices,
	}
}

// PromotionOrderCreator 是促销订单创建者结构体
type PromotionOrderCreator struct{}

// CreateOrder 创建促销订单,支持折扣参数
func (poc *PromotionOrderCreator) CreateOrder(items []string, prices []float64, discount ...float64) Order {
	var disc float64
	if len(discount) > 0 {
		disc = discount[0]
	} else {
		disc = 0
	}
	return &PromotionOrder{
		Items:    items,
		Prices:   prices,
		Discount: disc,
	}
}

func test2() {
	// 创建普通订单
	regularCreator := &RegularOrderCreator{}
	regularOrder := regularCreator.CreateOrder([]string{"Item1", "Item2"}, []float64{100.0, 200.0})
	regularOrder.Display()

	// 创建促销订单
	promotionCreator := &PromotionOrderCreator{}
	promotionOrder := promotionCreator.CreateOrder([]string{"Item3", "Item4"}, []float64{150.0, 250.0}, 0.1)
	promotionOrder.Display()
}

测试方法

func Test_test2(t *testing.T) {
	test2()
}

输出结果

=== RUN   Test_test2
Regular Order:
Item 1: Item1, Price: 100.00
Item 2: Item2, Price: 200.00
Total Price: 300.00
Promotion Order:
Item 1: Item3, Price: 150.00
Item 2: Item4, Price: 250.00
Total Price (after discount): 360.00
--- PASS: Test_test2 (0.00s)
PASS
;