public
Created

  • Download Gist
vehicle.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
package main
 
import (
"fmt"
)
 
type Vehicle struct {
speed int
}
 
func(v *Vehicle) Speed() int {
return v.speed
}
 
type Drivable interface {
Accelerate(delta uint)
Brake(delta uint)
Speed() int
}
 
type Car struct {
Vehicle
}
 
func(c *Car) Accelerate(delta uint) {
c.Vehicle.speed += int(delta)
}
 
func(c *Car) Brake(delta uint) {
c.Vehicle.speed -= int(delta)
}
 
 
func NewCar() Drivable {
c := new(Car)
c.Vehicle.speed = 0
return c
}
 
type Boat struct {
Vehicle
}
 
func(b *Boat) Accelerate(delta uint) {
b.Vehicle.speed += int(delta)
}
 
func(b *Boat) Brake(delta uint) {
b.Vehicle.speed -= int(delta)
}
 
func NewBoat() Drivable {
b := new(Boat)
b.Vehicle.speed = 0
return b
}
 
type Amphibian struct {
Car
Boat
swimming bool
}
 
func NewAmphibian() *Amphibian {
a := new(Amphibian)
a.swimming = false
return a
}
 
func(a *Amphibian) Swimming() bool {
return a.swimming
}
 
func(a *Amphibian) Swim(swim bool) {
a.swimming = swim
}
 
func(a *Amphibian) Accelerate(delta uint) {
if (a.swimming) {
a.Boat.Accelerate(delta)
} else {
a.Car.Accelerate(delta)
}
}
 
func(a *Amphibian) Brake(delta uint) {
if (a.swimming) {
a.Boat.Brake(delta)
} else {
a.Car.Brake(delta)
}
}
 
func(a *Amphibian) Speed() int {
if (a.swimming) {
return a.Boat.Speed()
}
return a.Car.Speed()
}
 
func main() {
c := NewCar()
fmt.Printf("car speed: %d kph\n", c.Speed())
c.Accelerate(20)
fmt.Printf("car speed: %d kph\n", c.Speed())
c.Brake(10)
fmt.Printf("car speed: %d kph\n", c.Speed())
 
b := NewBoat()
fmt.Printf("boat speed: %d kph\n", b.Speed())
 
a := NewAmphibian()
a.Accelerate(10)
a.Swim(true)
a.Accelerate(20)
fmt.Printf("amphibian speed swimming: %d kph\n", a.Speed())
a.Swim(false)
fmt.Printf("amphibian speed on land: %d kph\n", a.Speed())
 
var d Drivable
d = a
fmt.Printf("amphibian speed on land (as drivable): %d kph\n", d.Speed())
a.Swim(true)
fmt.Printf("amphibian speed swimming (as drivable): %d kph\n", d.Speed())
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.