0
我提出這個代碼試圖同時學習上去理解MVC架構不工作,和我被困試圖改變從控制器的模型值。二傳手在模型
的代碼現在創建一個模型,它僅保持一個字符串,該視圖顯示終端上的字符串,但是控制器不能改變它(它獲取用戶輸入沒有任何問題)。
現在我在終點站下車文字是這樣的:
Hello World!
asdf //my input
Hello World!
而且我想獲得的輸出會是這樣:
Hello World!
asdf //my input
asdf
這裏是我的文件:
model.go
package models
type IndexModel struct {
Text string
}
func (m *IndexModel) InitModel() string {
return m.Text
}
func (m *IndexModel) SetText(newText string) {
m.Text = newText
}
view.go
package views
import "github.com/jufracaqui/mvc_template/app/models"
type IndexView struct {
Model models.IndexModel
}
func (v IndexView) Output() string {
return v.Model.Text
}
controller.go
package controllers
import "github.com/jufracaqui/mvc_template/app/models"
type IndexController struct {
Model models.IndexModel
}
func (c IndexController) ChangeText(userInput string) {
c.Model.SetText(userInput)
}
main.go:
package main
import (
"bufio"
"os"
"fmt"
"github.com/jufracaqui/mvc_template/app/controllers"
"github.com/jufracaqui/mvc_template/app/models"
"github.com/jufracaqui/mvc_template/app/views"
)
func main() {
handleIndex()
}
func handleIndex() {
model := models.IndexModel{
"Hello World!",
}
controller := controllers.IndexController{
model,
}
viewIndex := views.IndexView{
model,
}
fmt.Println(viewIndex.Model.Text)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
controller.ChangeText(text)
fmt.Println(viewIndex.Model.Text)
}
編輯: 如何我的代碼結束了@JimB答案後:
model.go:
package models
type IndexModel struct {
Text string
}
func (m *IndexModel) InitModel() string {
return m.Text
}
view.go:
package views
import "github.com/jufracaqui/mvc_template/app/models"
type IndexView struct {
Model *models.IndexModel
}
func (v IndexView) Output() string {
return v.Model.Text
}
controller.go:
package controllers
import "github.com/jufracaqui/mvc_template/app/models"
type IndexController struct {
Model *models.IndexModel
}
func (c IndexController) ChangeText(userInput string) {
c.Model.Text = userImput
}
main.go:
package main
import (
"bufio"
"os"
"fmt"
"github.com/jufracaqui/mvc_template/app/controllers"
"github.com/jufracaqui/mvc_template/app/models"
"github.com/jufracaqui/mvc_template/app/views"
)
func main() {
handleIndex()
}
func handleIndex() {
model := models.IndexModel{
"Hello World!",
}
m := &model
controller := controllers.IndexController{
m,
}
viewIndex := views.IndexView{
m,
}
fmt.Println(viewIndex.Model.Text)
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
controller.ChangeText(text)
fmt.Println(viewIndex.Model.Text)
}
我很高興你沒有標註這個作爲的不斷所謂多結構二傳手問題重複。這個確實有一些細微的差別。 – RayfenWindspear