1
0
Fork 0
pr3-sose2026-fork/go/exercises/design_pattern/design_pattern.go

83 lines
1.6 KiB
Go

package main
import "fmt"
//Implementation of the factory design pattern:
type Transporter interface {
transport()
load()
unload()
}
type Truck struct {
name string
}
type Ship struct {
name string
}
var _ Transporter = Truck{} //Ensures that the "Transporter" Interface is implemented.
var _ Transporter = Ship{} //Ensures that the "Transporter" Interface is implemented.
func (t Truck) transport() {
fmt.Println("Transporting via ", t.name)
}
func (t Truck) load() {
fmt.Println("Loading cago on ", t.name)
}
func (t Truck) unload() {
fmt.Println("Unloading cargo from ", t.name)
}
func (t Ship) transport() {
fmt.Println("Transporting via ", t.name)
}
func (t Ship) load() {
fmt.Println("Loading cago on ", t.name)
}
func (t Ship) unload() {
fmt.Println("Unloading cargo from ", t.name)
}
type TransportFactory interface {
create(string) Transporter
}
type TruckFactory struct{}
type ShipFactory struct{}
func (TruckFactory) create(name string) Transporter {
return Truck{name}
}
func (ShipFactory) create(name string) Transporter {
return Ship{name}
}
var _ TransportFactory = TruckFactory{} //Ensures that the "TransportFactory" Interface is implemented.
var _ TransportFactory = ShipFactory{} //Ensures that the "TransportFactory" Interface is implemented.
func main() {
var shipFactory TransportFactory = ShipFactory{}
var truckFactory TransportFactory = TruckFactory{}
ship1 := shipFactory.create("evergreen")
ship1.load()
ship1.transport()
ship1.unload()
truck1 := truckFactory.create("scania")
truck1.load()
truck1.transport()
truck1.unload()
}