Golang 【第十二篇】簡單的項目實戰


Golang 【第十二篇】簡單的項目實戰   

 

 

 

一:家庭收支記賬軟件項目

1 面向過程

package main
import (
    "fmt"
)
func main() {
    //聲明一個變量,保存接收用戶輸入的選項
    key := ""
    //聲明一個變量,控制是否退出for
    loop := true

    //定義賬戶的余額 []
    balance := 10000.0
    //每次收支的金額
    money := 0.0
    //每次收支的說明
    note := ""
    //定義個變量,記錄是否有收支的行為
    flag := false
    //收支的詳情使用字符串來記錄
    //當有收支時,只需要對details 進行拼接處理即可
    details := "收支\t賬戶金額\t收支金額\t說    明"
    //顯示這個主菜單
    for {
        fmt.Println("\n-----------------家庭收支記賬軟件-----------------")
        fmt.Println("                  1 收支明細")
        fmt.Println("                  2 登記收入")
        fmt.Println("                  3 登記支出")
        fmt.Println("                  4 退出軟件")
        fmt.Print("請選擇(1-4):")
        fmt.Scanln(&key)

        switch key {
            case "1":
                fmt.Println("-----------------當前收支明細記錄-----------------")
                if flag {
                    fmt.Println(details)
                } else {
                    fmt.Println("當前沒有收支明細... 來一筆吧!")
                }
                
            case "2":
                fmt.Println("本次收入金額:")
                fmt.Scanln(&money)
                balance += money // 修改賬戶余額
                fmt.Println("本次收入說明:")
                fmt.Scanln(&note)
                //將這個收入情況,拼接到details變量
                //收入    11000           1000            有人發紅包
                details += fmt.Sprintf("\n收入\t%v\t%v\t%v", balance, money, note)
                flag = true

            case "3":
                fmt.Println("本次支出金額:")
                fmt.Scanln(&money)
                //這里需要做一個必要的判斷
                if money > balance {
                    fmt.Println("余額的金額不足")
                    break
                }
                balance -= money
                fmt.Println("本次支出說明:")
                fmt.Scanln(&note)
                details += fmt.Sprintf("\n支出\t%v\t%v\t%v", balance, money, note)
                flag = true
            case "4":
                fmt.Println("你確定要退出嗎? y/n")
                choice := ""
                for {

                    fmt.Scanln(&choice)
                    if choice == "y" || choice == "n" {
                        break
                    }
                    fmt.Println("你的輸入有誤,請重新輸入 y/n")
                }

                if choice == "y" {
                    loop = false
                }
            default :
                fmt.Println("請輸入正確的選項..")        
        }

        if !loop {
            break 
        }
    }
    fmt.Println("你退出家庭記賬軟件的使用...")
}
面向過程

2 面向對象

package main
import (
    "go_code/familyaccount/utils"
    "fmt"
)
func main() {

    fmt.Println("這個是面向對象的方式完成~~")
    utils.NewFamilyAccount().MainMenu() //思路非常清晰
}
main/main.go
package utils
import (
    "fmt"
)

type FamilyAccount struct {
    //聲明必須的字段.

    //聲明一個字段,保存接收用戶輸入的選項
    key  string
    //聲明一個字段,控制是否退出for
    loop bool
    //定義賬戶的余額 []
    balance float64
    //每次收支的金額
    money float64
    //每次收支的說明
    note string
    //定義個字段,記錄是否有收支的行為
    flag bool
    //收支的詳情使用字符串來記錄
    //當有收支時,只需要對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("當前沒有收支明細... 來一筆吧!")
    }
} 

//將登記收入寫成一個方法,和*FamilyAccount綁定
func (this *FamilyAccount) income() {
    
    fmt.Println("本次收入金額:")
    fmt.Scanln(&this.money)
    this.balance += this.money // 修改賬戶余額
    fmt.Println("本次收入說明:")
    fmt.Scanln(&this.note)
    //將這個收入情況,拼接到details變量
    //收入    11000           1000            有人發紅包
    this.details += fmt.Sprintf("\n收入\t%v\t%v\t%v", this.balance, this.money, this.note)
    this.flag = true
}

//將登記支出寫成一個方法,和*FamilyAccount綁定
func (this *FamilyAccount) pay() {
    fmt.Println("本次支出金額:")
    fmt.Scanln(&this.money)
    //這里需要做一個必要的判斷
    if this.money > this.balance {
        fmt.Println("余額的金額不足")
        //break
    }
    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.flag = true
}

//將退出系統寫成一個方法,和*FamilyAccount綁定
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" {
        this.loop = false
    }
}


//給該結構體綁定相應的方法
//顯示主菜單
func (this *FamilyAccount) MainMenu() {

    for {
        fmt.Println("\n-----------------家庭收支記賬軟件-----------------")
        fmt.Println("                  1 收支明細")
        fmt.Println("                  2 登記收入")
        fmt.Println("                  3 登記支出")
        fmt.Println("                  4 退出軟件")
        fmt.Print("請選擇(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("請輸入正確的選項..")        
        }

        if !this.loop {
            break 
        }

    }
}
utils/familyAccount.go

 

二:客戶信息關系系統

程序框架圖

 

 mvc目錄

 

 

package model
import (
    "fmt"
)
//聲明一個Customer結構體,表示一個客戶信息 

type Customer struct {
    Id int 
    Name string
    Gender string
    Age int
    Phone string
    Email string
}

//使用工廠模式,返回一個Customer的實例 

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,
    }
}

//第二種創建Customer實例方法,不帶id
func NewCustomer2(name string, gender string, 
    age int, phone string, email string ) Customer {
    return Customer{
        Name : name,
        Gender : gender,
        Age : age,
        Phone : phone,
        Email : email,
    }
}

//返回用戶的信息,格式化的字符串
func (this Customer) GetInfo()  string {
    info := fmt.Sprintf("%v\t%v\t%v\t%v\t%v\t%v\t", this.Id, 
        this.Name, this.Gender,this.Age, this.Phone, this.Email)
    return info

}
1 model/customer.go
package service
import (
    "go_code/customerManage/model"

)

//該CustomerService, 完成對Customer的操作,包括
//增刪改查
type CustomerService struct {
    customers []model.Customer
    //聲明一個字段,表示當前切片含有多少個客戶
    //該字段后面,還可以作為新客戶的id+1
    customerNum int 
}

//編寫一個方法,可以返回 *CustomerService
func NewCustomerService() *CustomerService {
    //為了能夠看到有客戶在切片中,我們初始化一個客戶
    customerService := &CustomerService{}
    customerService.customerNum = 1
    customer := model.NewCustomer(1, "張三", "", 20, "112", "zs@sohu.com")
    customerService.customers = append(customerService.customers, customer)
    return customerService
}

//返回客戶切片
func (this *CustomerService) List() []model.Customer {
    return this.customers
}

//添加客戶到customers切片
//!!!
func (this *CustomerService) Add(customer model.Customer) bool {

    //我們確定一個分配id的規則,就是添加的順序
    this.customerNum++
    customer.Id = this.customerNum
    this.customers = append(this.customers, customer)
    return true
}

//根據id刪除客戶(從切片中刪除)
func (this *CustomerService) Delete(id int) bool {
    index := this.FindById(id)
    //如果index == -1, 說明沒有這個客戶
    if index == -1 {
        return false 
    }
    //如何從切片中刪除一個元素
    this.customers = append(this.customers[:index], this.customers[index+1:]...)
    return true
}

//根據id查找客戶在切片中對應下標,如果沒有該客戶,返回-1
func (this *CustomerService) FindById(id int)  int {
    index := -1
    //遍歷this.customers 切片
    for i := 0; i < len(this.customers); i++ {
        if this.customers[i].Id == id {
            //找到
            index = i
        }
    }
    return index
}
2 service/customerService.go
package main

import (
    "fmt"
    "go_code/customerManage/service"
    "go_code/customerManage/model"
)

type customerView struct {

    //定義必要字段
    key string //接收用戶輸入...
    loop bool  //表示是否循環的顯示主菜單
    //增加一個字段customerService
    customerService *service.CustomerService

}

//顯示所有的客戶信息
func (this *customerView) list() {

    //首先,獲取到當前所有的客戶信息(在切片中)
    customers := this.customerService.List()
    //顯示
    fmt.Println("---------------------------客戶列表---------------------------")
    fmt.Println("編號\t姓名\t性別\t年齡\t電話\t郵箱")
    for i := 0; i < len(customers); i++ {
        //fmt.Println(customers[i].Id,"\t", customers[i].Name...)
        fmt.Println(customers[i].GetInfo())
    }
    fmt.Printf("\n-------------------------客戶列表完成-------------------------\n\n")
}

//得到用戶的輸入,信息構建新的客戶,並完成添加
func (this *customerView) add() {
    fmt.Println("---------------------添加客戶---------------------")
    fmt.Println("姓名:")
    name := ""
    fmt.Scanln(&name)
    fmt.Println("性別:")
    gender := ""
    fmt.Scanln(&gender)
    fmt.Println("年齡:")
    age := 0
    fmt.Scanln(&age)
    fmt.Println("電話:")
    phone := ""
    fmt.Scanln(&phone)
    fmt.Println("電郵:")
    email := ""
    fmt.Scanln(&email)
    //構建一個新的Customer實例
    //注意: id號,沒有讓用戶輸入,id是唯一的,需要系統分配
    customer := model.NewCustomer2(name, gender, age, phone, email)
    //調用
    if this.customerService.Add(customer) {
        fmt.Println("---------------------添加完成---------------------")
    } else {
        fmt.Println("---------------------添加失敗---------------------")
    }
}

//得到用戶的輸入id,刪除該id對應的客戶
func (this *customerView) delete() {
    fmt.Println("---------------------刪除客戶---------------------")
    fmt.Println("請選擇待刪除客戶編號(-1退出):")
    id := -1
    fmt.Scanln(&id)
    if id == -1 {
        return //放棄刪除操作
    }
    fmt.Println("確認是否刪除(Y/N):")
    //這里同學們可以加入一個循環判斷,直到用戶輸入 y 或者 n,才退出..
    choice := ""
    fmt.Scanln(&choice)
    if choice == "y" || choice == "Y" {
        //調用customerService 的 Delete方法
        if this.customerService.Delete(id) {
            fmt.Println("---------------------刪除完成---------------------")
        } else {
            fmt.Println("---------------------刪除失敗,輸入的id號不存在----")
        }
    }
}

//退出軟件 
func (this *customerView) exit() {

    fmt.Println("確認是否退出(Y/N):")
    for {
        fmt.Scanln(&this.key)
        if this.key == "Y" || this.key == "y" || this.key == "N" || this.key == "n" {
            break
        }

        fmt.Println("你的輸入有誤,確認是否退出(Y/N):")
    }

    if this.key == "Y" || this.key == "y" {
        this.loop = false
    }

}

//顯示主菜單
func (this *customerView) mainMenu() {

    for {
        
        fmt.Println("-----------------客戶信息管理軟件-----------------")
        fmt.Println("                 1 添 加 客 戶")
        fmt.Println("                 2 修 改 客 戶")
        fmt.Println("                 3 刪 除 客 戶")
        fmt.Println("                 4 客 戶 列 表")
        fmt.Println("                 5 退       出")
        fmt.Print("請選擇(1-5):")

        fmt.Scanln(&this.key)
        switch this.key {
            case "1" :
                this.add()
            case "2" :
                fmt.Println("修 改 客 戶")
            case "3" :
                this.delete()
            case "4" :
                this.list()
            case "5" :
                this.exit()
            default :
                fmt.Println("你的輸入有誤,請重新輸入...")
        }

        if !this.loop {
            break
        }

    }
    fmt.Println("你退出了客戶關系管理系統...")
}



func main() {
    //在main函數中,創建一個customerView,並運行顯示主菜單..
    customerView := customerView{
        key : "",
        loop : true,
    }
    //這里完成對customerView結構體的customerService字段的初始化
    customerView.customerService = service.NewCustomerService()
    //顯示主菜單..
    customerView.mainMenu()

}
3 view/customerView.go

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM