Abstract factory pattern

This commit is contained in:
Jian Han 2018-01-14 15:43:41 +10:00
parent 61fd1de9d7
commit ecef7a4803
12 changed files with 131 additions and 0 deletions

BIN
channel/basic/debug Executable file

Binary file not shown.

View File

@ -0,0 +1,5 @@
package main
type Car interface {
NumDoors() int
}

View File

@ -0,0 +1,24 @@
package main
import (
"errors"
"fmt"
)
const (
LuxuryCarType = 1
FamilyCarType = 2
)
type CarFactory struct{}
func (c *CarFactory) NewVehicle(v int) (Vehicle, error) {
switch v {
case LuxuryCarType:
return new(LuxuryCar), nil
case FamilyCarType:
return new(FamilyCar), nil
default:
return nil, errors.New(fmt.Sprintf("Vehicle of type %d not exist\n", v))
}
}

View File

@ -0,0 +1,15 @@
package main
type CruiseMotorbike struct{}
func (s *CruiseMotorbike) NumWheels() int {
return 2
}
func (s *CruiseMotorbike) NumSeats() int {
return 2
}
func (s *CruiseMotorbike) GetMotorbikeType() int {
return CruiseMotorbikeType
}

View File

@ -0,0 +1,15 @@
package main
type FamilyCar struct{}
func (*FamilyCar) NumDoors() int {
return 5
}
func (*FamilyCar) NumWheels() int {
return 4
}
func (*FamilyCar) NumSeats() int {
return 5
}

View File

@ -0,0 +1,15 @@
package main
type LuxuryCar struct{}
func (*LuxuryCar) NumDoors() int {
return 4
}
func (*LuxuryCar) NumWheels() int {
return 4
}
func (*LuxuryCar) NumSeats() int {
return 5
}

View File

@ -9,3 +9,5 @@ package main
// Objectives: Grouping related families of objects is very convenient when your object number is growing so much that
// creating a unique point to get them all seems the only way to gain the flexible of runtime object creation.

View File

@ -0,0 +1,5 @@
package main
type Motorbike interface {
GetMotorbikeType() int
}

View File

@ -0,0 +1,24 @@
package main
import (
"errors"
"fmt"
)
const (
SportMotorbikeType = 1
CruiseMotorbikeType = 2
)
type MotorbikeFactory struct{}
func (m *MotorbikeFactory) Build(v int) (Vehicle, error) {
switch v {
case SportMotorbikeType:
return new(SportMotorbike), nil
case CruiseMotorbikeType:
return new(CruiseMotorbike), nil
default:
return nil, errors.New(fmt.Sprintf("Motor bike of type %d not exist\n", v))
}
}

View File

@ -0,0 +1,15 @@
package main
type SportMotorbike struct{}
func (s *SportMotorbike) NumWheels() int {
return 2
}
func (s *SportMotorbike) NumSeats() int {
return 1
}
func (s *SportMotorbike) GetMotorbikeType() int {
return SportMotorbikeType
}

View File

@ -0,0 +1,6 @@
package main
type Vehicle interface {
NumWheels() int
NumSeats() int
}

View File

@ -0,0 +1,5 @@
package main
type VehicleFactory interface {
NewVehicle(v int) (Vehicle, error)
}