接口封裝
package utils
import (
"fmt"
)
//定義結構體
type FamilyAccount struct{
key string
loop bool
balance float64
money float64
note string
details string
flags bool
}
//編寫要給工廠模式的構造方法
func NewFamilyAccount() *FamilyAccount{
return &FamilyAccount{
key:"",
loop:true,
balance:10000.0,
money:0.0,
note:"",
flags:false,
details:"收支\t賬戶金額\t收支金額\t說 明\t",
}
}
//主體業務邏輯
func (this*FamilyAccount)InitMainPage(){
fmt.Println("---------------家庭收支記賬軟體---------------")
fmt.Println("---------------1,收支明細---------------")
fmt.Println("---------------2,登記收入---------------")
fmt.Println("---------------3,登記支出---------------")
fmt.Println("---------------4,退出軟體---------------")
fmt.Println("----------------------------------------")
fmt.Println("請選擇1-4:")
for{
fmt.Scanln(&this.key)
switch this.key {
case "1":
this.ShowDetail()
case "2":
this.inCome()
case "3":
this.outCome()
case "4":
this.logout()
default:
selectErr()
}
if !this.loop {
break
}
}
fmt.Println("---------------你選擇了退出軟體,再會!---------------")
}
//收支明細
func (this*FamilyAccount)ShowDetail(){
fmt.Println("---------------1,收支明細---------------")
if this.flags{
fmt.Println(this.details)
} else{
fmt.Println("目前沒有收支記錄,來記錄一筆吧!")
}
}
//登記收入
func (this*FamilyAccount)inCome(){
fmt.Println("---------------2,登記收入---------------")
fmt.Println("本次收入的金額:")
fmt.Scanln(&this.money)
this.balance += this.money
fmt.Println("本次收入的說明:")
fmt.Scanln(&this.note)
this.details += fmt.Sprintf("\n收入\t%v\t%v\t%v",this.balance,this.money,this.note)
this.flags = true
}
//支出記錄
func (this*FamilyAccount)outCome(){
fmt.Println("---------------3,登記支出---------------")
fmt.Println("本次支出的金額:")
fmt.Scanln(&this.money)
if this.money > this.balance{
fmt.Println("金額不足")
return
}
this.balance -= this.money
fmt.Println("本次支出的說明:")
fmt.Scanln(&this.note)
this.details += fmt.Sprintf("\n收入\t%v\t%v\t%v",this.balance,this.money,this.note)
this.flags = true
}
//退出軟體
func (this*FamilyAccount)logout(){
fmt.Println("---------------4,退出軟體---------------")
fmt.Println("你确定要退出嗎?(y/n)")
choice := ""
for{
fmt.Scanln(&choice)
if choice == "y" || choice == "n"{
break
}
fmt.Println("輸入格式有誤,請重新輸入(y/n)")
}
if choice == "y"{
this.loop = false
}
}
//錯誤選擇
func selectErr(){
fmt.Println("---------------你的選擇不正确---------------")
}
調用方式
package main
import(
"fmt"
"project/utils"
)
func main(){
fmt.Println("面向對象程式設計模式,接口封裝")
utils.NewFamilyAccount().InitMainPage()
}