【问题标题】:Setting up a Factory Pattern in Go在 Go 中设置工厂模式
【发布时间】:2017-05-12 20:50:32
【问题描述】:

我目前有一个工厂模式设置,但是在显式初始化返回的对象时,我无法让它们记住任何内容。

我有以下文件:

carBase.go

package Cars

//base class for car factory
type car interface {
  Initialise(string, string)
  SayCar()
}

toyota.go

package Cars

import (
    "fmt"
)

type toyotaCar struct {
  carType string
  colour string
}

func (car toyotaCar) Initialise(col, carType string){

  car.colour = col
  car.carType = carType

}

func (car toyotaCar) SayCar(){
  fmt.Println(car.carType)
  fmt.Println(car.colour)
}

carFactory.go

package Cars

func GetCar(carType string) (car) {

  switch carType {
  case "toyota":
    return new(toyotaCar)
  }

  return new(toyotaCar)

}

最后是 main.go

package main

import (
  "FactoryTest/Cars"
  "fmt"
)

func main() {

  car := Cars.GetCar("toyota")
  fmt.Println(car)
  car.Initialise("thing" , "otherthing")
  fmt.Println(car)
  car.SayCar()
  fmt.Println(car)

}

在每个fmt.Printn(car) 行中,我得到&{ },这表明没有设置任何内容。当我运行car.SayCar() 时,什么都没有打印出来。

我只是想在这里强迫这个问题,还是我缺少一些简单的东西来完成这项工作?

【问题讨论】:

  • 真的解决了,谢谢!

标签: go factory


【解决方案1】:

问题在于不使用指针,而汽车被方法所占用:

toyota.go 变成:

package Cars

import (
    "fmt"
)

type toyotaCar struct {
  carType string
  colour string
}

func (car *toyotaCar) Initialise(col, carType string){

  car.colour = col
  car.carType = carType

}

func (car *toyotaCar) SayCar(){
  fmt.Println(car.carType)
  fmt.Println(car.colour)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多