69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package main
|
|
|
|
import "fmt"
|
|
|
|
/*
|
|
实例:
|
|
汤宝宝买火车票,可以去火车站买,也可以去代售点买,但是汤宝宝选择全都要。然而,火车站总共只剩两张票,这可苦了小明了。
|
|
*/
|
|
|
|
type Seller interface {
|
|
Sell(name string) error
|
|
}
|
|
|
|
type TrainStation struct {
|
|
stock int
|
|
}
|
|
|
|
func newTrainStation(stock int) *TrainStation {
|
|
fmt.Printf("火车站库存%d张票\n", stock)
|
|
return &TrainStation{stock: stock}
|
|
}
|
|
|
|
func (ts *TrainStation) Sell(name string) error {
|
|
fmt.Printf("%s去火车站买票。\n", name)
|
|
if ts.stock > 0 {
|
|
ts.stock--
|
|
fmt.Printf("%s在火车站买到一张火车票。\n", name)
|
|
return nil
|
|
} else {
|
|
fmt.Printf("火车站没有票了, %s没买到票。\n", name)
|
|
return fmt.Errorf("no ticket")
|
|
}
|
|
}
|
|
|
|
type TicketAgency struct {
|
|
name string
|
|
station *TrainStation
|
|
}
|
|
|
|
func newTicketAgency(name string, station *TrainStation) *TicketAgency {
|
|
return &TicketAgency{name: name, station: station}
|
|
}
|
|
|
|
func (tp *TicketAgency) Sell(name string) error {
|
|
fmt.Printf("%s去%s买票。\n", name, tp.name)
|
|
err := tp.station.Sell(tp.name)
|
|
if err != nil {
|
|
fmt.Printf("%s在%s没买到票。\n", name, tp.name)
|
|
return err
|
|
}
|
|
fmt.Printf("%s在%s买到一张火车票。\n", name, tp.name)
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("============= 代理模式 =============")
|
|
station := newTrainStation(2)
|
|
agency := newTicketAgency("代售点A", station)
|
|
station.Sell("汤宝宝")
|
|
agency.Sell("汤宝宝")
|
|
|
|
fmt.Println()
|
|
agency.Sell("小明")
|
|
station.Sell("小明")
|
|
|
|
fmt.Println()
|
|
fmt.Println("=========== 代理模式结束 ===========")
|
|
}
|