view层的对象customerView,一般为了逻辑上比较好区分view层的对象命名和view层相关。其中包含三个字段,
1.key:key的数值表示所选择的服务类型,也就是view层的显示。
fmt.Println("-------------客户信息管理软件-------------")
fmt.Println(" 1.添加客户")
fmt.Println(" 2.修改客户")
fmt.Println(" 3.删除客户")
fmt.Println(" 4.客户列表")
fmt.Println(" 5.退 出")
2.loop:loop表示是否来循环的显示主菜单。
3.customerService字段表示是service层的cutomerService
为什么要将service层的customerService来加入到view层的结构体?因为将service层的CustomerService加入到view层,就可以在view层调用service层的方法。
service层的结构体如下:其中customers是model层的结构体,包含最基本的信息。
type CustomerService struct {
customers []model.Customer
costomerNum int //声明一个字段,表示当前该切片有多少个客户,还可以作为新客户的id号
}
type customerView struct {
//定义必要字段
key string
loop bool //表示是否循环的显示主菜单
//增加一个字段customerService
customerService *service.CustomerService
}
service层的CustomerService结构体包含model层的最基本的结构体customer的一个切片
type CustomerService struct {
customers []model.Customer
costomerNum int //声明一个字段,表示当前该切片有多少个客户,还可以作为新客户的id号
}
model层的是最基础的结构体,
type Customer struct {
Id int
Name string
Gender string
Age int
Phone string
Email string
}
view层List方法:
view层的list可以调用service层的list方法,因为service层的结构体被包含在了view层的结构体之中,而他的返回类型是由model层的最基本的customer结构体所组成的一个切片。
func (this *CustomerService) List() []model.Customer {
return this.customers //这个customers是CustomerService中的一个字段,她的数据类型是model中的Customer所组成的一个customers类型的切片
}
//显示所有的客户信息
func (this *customerView) List() {
//首先,获取到当前所有的客户信息,都在切片中
customers := this.customerService.List() //list去调用customerService的List方法,并显示客户列表。
//因为this是customerView类型,包含customerService字段可以调用service层的方法。
//显示
fmt.Println("-------------客户列表-------------")
fmt.Println("编号\t姓名\t性别\t年龄\t电话\t邮箱")
for i := 0; i < len(customers); i++ {
fmt.Println(customers[i].GetInfo())
}
fmt.Println("-----------客户列表完成-------------")
}
view层的mainMenu函数,接受的是一个customerView的数据类型,customerView是view层的一个结构体类型,包含有所需要的所有的字段。
func (this *customerView) mainMenu() {
for {
fmt.Println("-------------客户信息管理软件-------------")
fmt.Println(" 1.添加客户")
fmt.Println(" 2.修改客户")
fmt.Println(" 3.删除客户")
fmt.Println(" 4.客户列表")
fmt.Println(" 5.退 出")
fmt.Println("请选择(1-5)")
fmt.Scanln(&this.key)
switch this.key {
case "1":
fmt.Println("添加客户")
case "2":
fmt.Println("修改客户")
case "3":
fmt.Println("删除客户")
case "4":
this.List()
case "5":
this.loop = false
default:
fmt.Println("你的输入有误,请重新输入")
}
if !this.loop {
break
}
}
fmt.Println("你退出了客户管理系统")
}
在view层的主函数调用中,因为customerView有三个字段,首先给其中两个字段赋值。接着调用serivce层的NewCustomerService方法来进行初始化CustomerService字段,而CustomerService字段又可以调用model层的初始化customer的方法。
func main() {
//在main函数中,创建一个CustomerView实例,并运行显示主菜单
customerView := customerView{
key: "",
loop: true,
}
//这里完成对customerView结构体的customerService字段的初始化
customerView.customerService = customerservice.NewCustomerService() //这里view层的customerView已经包含了customerService这个类型的结构体,
//而且已经被初始化了
customerView.mainMenu()
}
model层的初始化customer的方法。
//使用工厂模式,返回一个model实例
func NewCustomer(id int, name string, gender string, age int, phone string, email string) Customer {
return Customer{
Id: id,
Name: name,
Gender: gender,
Age: age,
Phone: phone,
Email: email,
}
}