英文:
Setting up a Factory Pattern in Go
问题
我目前有一个工厂模式的设置,但是当我显式初始化返回的对象时,我遇到了一些问题。
我有以下文件:
carBase.go
package Cars
//汽车工厂的基类
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()
时,没有任何输出。
我是不是在强行解决问题,还是有什么简单的东西我忽略了,以使其工作?
英文:
I have a factory pattern setup at the moment but I'm having trouble getting the returned objects to remember anything when explicitly initialising them.
I have the following files:
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)
}
and finally 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)
}
In each of the fmt.Printn(car)
lines, I'm getting &{ }
which indicates that nothing is being set. When I run car.SayCar()
nothing prints out.
Am I just trying to force the issue here, or is there something simple that I'm missing to make this work?
答案1
得分: 2
问题出在没有在方法中使用指针来处理被接收的汽车:
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)
}
英文:
The issue was with not using pointers with the car being taken in by the methods:
toyota.go becomes:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论