本文通过一个接口(CommonWork)将两种类型(Class、Company)的调用功能(Entry、Graduate)进行抽象。
- 功能抽象:两种类型通过同一个接口调用方法,实现了合理的封装和抽象;
- 降低使用成本:使用该方法的人仅关注入参和返回值即可使用类似的功能。
文件列表
project
├── class
│ └── class.go
└── main.go
// project/class/class.go
//实现了两种类型通过同一个接口调用方法,可以实现合理的封装。
//使用该方法的人仅关注入参和返回值即可使用类似的功能
package class
type CommonWork interface {
Entry(string) //入职
Graduate(string) //毕业
}
type Class struct {
StudentList []string //学生列表
}
type Company struct {
EmployeeList []string //员工列表
}
//学生入学
func (c *Class) Entry(studentName string) {
c.StudentList = append(c.StudentList, studentName)
}
//学生毕业
func (c *Class) Graduate(studentOut string) {
for i, v := range c.StudentList {
if v == studentOut {
c.StudentList = append(c.StudentList[0:i], c.StudentList[i+1:len(c.StudentList)]...)
break
}
}
}
//员工入职
func (c *Company) Entry(employeeName string) {
c.EmployeeList = append(c.EmployeeList, employeeName)
}
//员工离职
func (c *Company) Graduate(employeeName string) {
for i, v := range c.EmployeeList {
if v == employeeName {
c.EmployeeList = append(c.EmployeeList[0:i], c.EmployeeList[i+1:len(c.EmployeeList)]...)
break
}
}
}
package main
import (
"fmt"
"project/class"
)
func main() {
var classA = &class.Class{StudentList: []string{"小红", "小明"}}
FarewellStudent(classA, "小红") //因为interface是指针类型,所以classA为指针类型
fmt.Println(classA.StudentList) //输出 [小明]
var companyA = new(class.Company) //或者 var companyA = &class.Company{}
WelcomeEmployee(companyA, "John") //同上,所以companyA为指针类型
fmt.Println(companyA.EmployeeList) //输出[John]
//---------------------interface方便了下面的使用----------------
//欢迎学生
func WelcomeStudent(c class.CommonWork, student string) {
// 注意这里的c的类型是interface, 需要具体的类型实现该接口
c.Entry(student)
}
//欢送学生
func FarewellStudent(c class.CommonWork, student string) {
c.Graduate(student)
}
//欢迎员工
func WelcomeEmployee(c class.CommonWork, employee string) {
c.Entry(employee)
}
//欢送员工
func FarewellEmployee(c class.CommonWork, employee string) {
c.Graduate(employee)
}
}