【Go】面向对象(四):面向对象实战(图书借阅系统demo)

package main

import "fmt"

type Book struct{
    
    
	BookId string
	Name string
	Price float64
	Author string
	Borrowable bool
}
type Reader struct {
    
    
	//读者ID
	ReaderID string
	//押金余额
	Balance float64
}

func (r *Reader)BorrowBook(b *Book)  {
    
    
	if b.Borrowable{
    
    
		b.Borrowable = false
		fmt.Printf("读者%s借阅了%s\n",r.ReaderID,b.Name)
	}else {
    
    
		fmt.Printf("%s借阅失败,该书已借出", b.Name)
	}
}
func (r *Reader)ReturnBook(b *Book)  {
    
    
	fmt.Printf("读者%s归还了%s\n",r.ReaderID,b.Name)
}
func (r *Reader)PayPenalty(amount float64)  {
    
    
	r.Balance-=amount
	fmt.Printf("%s交纳了罚金%.2f元,余额是%.2f元\n",r.ReaderID,amount,r.Balance)

}
//学生数据模型
type Student struct {
    
    
	//继承
	Reader
	//学生特有属性
	Name string
	Major string

}

func (s *Student) Study ()  {
    
    
	fmt.Printf("%s正在学习\n",s.Name)
}

type Teacher struct {
    
    
	//继承Reader
	Reader
	//老师特有属性
	Name string
	Course string

}

func (t *Teacher) Teach ()  {
    
    
	fmt.Printf("%s正在教授%s\n",t.Name,t.Course)
}
//覆写交罚金方法:老师不交罚金
func (t *Teacher)PayPenalty(amount float64)  {
    
    
	fmt.Printf("%s交纳了罚金%.2f元,余额是%.2f元\n",t.ReaderID,amount,t.Balance)

}
func main() {
    
    
	//创建书
	b1 := Book{
    
    }
	b1.Name="银瓶梅"
	b1.Author="欧阳搏达"
	b1.Price=999.9
	b1.Borrowable=true

	b2 := Book{
    
    "10001","奥力给",998.0,"yangge",true}
	b3 := Book{
    
    "10002", "黄金时代", 100.0, "王小波",true}
	b4Ptr := new(Book)
	b4Ptr.Name="蓝楼梦"
	b4Ptr.Author="欧阳搏达"
	b4Ptr.Price=9.9
	b4Ptr.Borrowable=true

	fmt.Println(b1,b2,b3,b4Ptr)
	//创建学生和老师
	s1 := Student{
    
    
		Reader: Reader{
    
    "001", 100},
		//s1:=Student{r1,"狗蛋","Python"}
		Name:   "狗蛋",
		Major:  "Python",
	}
	fmt.Printf("%v\n",s1)
	fmt.Printf("%+v\n",s1)
	fmt.Printf("%#v\n",s1)

	t1 := Teacher{
    
    
		Reader: Reader{
    
    "002", 0},
		Name:   "老王",
		Course: "撩妹秘籍",
	}
	fmt.Printf("%v\n",t1)
	fmt.Printf("%+v\n",t1)
	fmt.Printf("%#v\n",t1)

	//教学、学习、借书、还书、交罚款、状态
	t1.Teach()
	s1.Study()
	t1.BorrowBook(&b1)
	t1.BorrowBook(b4Ptr)
	s1.BorrowBook(&b3)
	s1.BorrowBook(&b2)

	t1.ReturnBook(&b1)
	s1.ReturnBook(&b2)
	t1.ReturnBook(b4Ptr)

	s1.PayPenalty(5)
}

猜你喜欢

转载自blog.csdn.net/qq_36045898/article/details/114047429