golang学习(十四):记账软件项目(二)
说明:上一篇通过面向过程实现了家庭记账软件的基本功能,现在改成面向对象。
思路:把记账软件的功能封装到一个结构体,然后调用该结构体的方法来实现。
代码如下:
main.go
package main
import (
"awesomeProject3/utils"
"fmt"
)
func main() {
fmt.Println("这个是面向对象的方式完成..")
//调用主菜单MainMenu()
utils.NewFamilyAccount().MainMenu()
}
familyAccount.go
package utils
import "fmt"
//面向对象家庭收支记账软件
type FamilyAccount struct {
//保存用户输入的数据
key string
//控制是否退出for循环
loop bool
//账户的余额:balance
balance float64
//收支的金额:money
money float64
//收支的说明:note
note string
//记录是否有收支的行为的一个变量 :flag
flag bool
//收支的详情:details
//当有收支时,对details进行拼接处理
details string
}
//编写工厂模式的构造方法,返回一个*FamilyAccount实例
func NewFamilyAccount() *FamilyAccount {
return &FamilyAccount{
key: "",
loop: true,
balance: 10000.0,
money: 0.0,
note: "",
flag: false,
details: "详情\t账户金额\t收支金额\t说明",
}
}
//将显示明细写成一个方法
func (this *FamilyAccount) showDetails() {
fmt.Println("-------------当前收支明细记录--------------")
//当有收支时,显示收支详情
if this.flag {
fmt.Println(this.details)
} else {
fmt.Println("暂时没有收支..")
}
}
//将登记收入写成一个方法
func (this *FamilyAccount) income() {
fmt.Println("---------------登记收入--------------------")
fmt.Println("本次收入金额:")
//用户输入收入金额
fmt.Scanln(&this.money)
//用户余额便发生变化
this.balance += this.money
fmt.Println("本次收入说明:")
//用户输入收入说明
fmt.Scanln(&this.note)
//将收入情况拼接到details变量
this.details += fmt.Sprintf("\n收入\t%v\t%v\t%v", this.balance, this.money, this.note)
this.flag = true
}
//将登记支出写成一个方法
func (this *FamilyAccount) pay() {
fmt.Println("---------------登记支出--------------------")
fmt.Println("本次支出金额:")
//用户输入支出金额
fmt.Scanln(&this.money)
//根据用户余额对支出的金额做出判断
if this.money > this.balance {
fmt.Println("你的余额不足,请重新输入...")
//break
}
//支出后用户的余额发生变化
this.balance -= this.money
fmt.Println("本次支出说明:")
fmt.Scanln(&this.note)
//将支出情况拼接到details变量
this.details += fmt.Sprintf("\n支出\t%v\t%v\t%v", this.balance, this.money, this.note)
this.flag = true
}
//将退出系统写成一个方法
func (this *FamilyAccount) exit() {
fmt.Println("你确定要退出吗? y/n")
choice := ""
for {
fmt.Scanln(&choice)
if choice == "y" || choice == "n" {
break
}
fmt.Println("你的输入有误,请重新输入y/n")
}
if choice == "y" {
fmt.Println("你已经退出系统..")
this.loop = false
}
}
//给结构体绑定方法
//显示主菜单
func (this *FamilyAccount) MainMenu() {
for {
//显示主菜单
fmt.Println("\n-------------家庭收支记账软件-------------")
fmt.Println(" 1 收支明细")
fmt.Println(" 2 登记收入")
fmt.Println(" 3 登记支出")
fmt.Println(" 4 退出软件")
fmt.Println("请选择(1-4):")
//接收用户输入(1-4)
fmt.Scanln(&this.key)
//对用户输入进行判断
switch this.key {
case "1":
//调用
this.showDetails()
case "2":
this.income()
case "3":
this.pay()
case "4":
this.exit()
default:
fmt.Println("请输入" +
"正确的选项")
}
//退出for循环
if !this.loop {
break
}
}
}
项目运行页面:
更多测试页面参考上一篇:golang学习(十三):记账软件项目
欢迎大家指正补充,感谢阅读。