设计模式 - 服务定位器模式
Go Channel Practice V - 祖安萝莉

设计模式 - 传输对象模式

violet posted @ 5 年前 in 笔记 with tags Design Pattern Golang , 477 阅读

传输对象模式(Transfer Object Pattern)用于从客户端向服务器一次性传递带有多个属性的数据。传输对象也被称为数值对象。传输对象是一个具有 getter/setter 方法的简单的 POJO 类,它是可序列化的,所以它可以通过网络传输。它没有任何的行为。服务器端的业务类通常从数据库读取数据,然后填充 POJO,并把它发送到客户端或按值传递它。对于客户端,传输对象是只读的。客户端可以创建自己的传输对象,并把它传递给服务器,以便一次性更新数据库中的数值。以下是这种设计模式的实体。

  • 业务对象(Business Object) - 为传输对象填充数据的业务服务。
  • 传输对象(Transfer Object) - 简单的 POJO,只有设置/获取属性的方法。
  • 客户端(Client) - 客户端可以发送请求或者发送传输对象到业务对象。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
 
import "fmt"
 
type StudentVO struct {
    Name   string
    RollNo int
}
 
func NewStudentVO(name string, rollNo int) *StudentVO {
    return &StudentVO{
        Name:   name,
        RollNo: rollNo,
    }
}
 
func (s *StudentVO) GetName() string {
    return s.Name
}
 
func (s *StudentVO) SetName(name string) {
    s.Name = name
}
 
func (s *StudentVO) GetRollNo() int {
    return s.RollNo
}
 
func (s *StudentVO) SetRollNo(no int) {
    s.RollNo = no
}
 
type StudentBO struct {
    Students []*StudentVO
}
 
func NewStudentBO() *StudentBO {
    return &StudentBO{
        Students: []*StudentVO{
            &StudentVO{"Robert", 1},
            &StudentVO{"John", 2},
        },
    }
}
 
func (s *StudentBO) Delete(student *StudentVO) {
    for i := 0; i < len(s.Students); i++ {
        if s.Students[i].RollNo == student.RollNo {
            s.Students[i] = s.Students[len(s.Students)-1]
            s.Students = s.Students[:len(s.Students)-1]
            return
        }
    }
}
 
func (s *StudentBO) GetAllStudents() []*StudentVO {
    return s.Students
}
 
func (s *StudentBO) GetStudent(no int) *StudentVO {
    for _, item := range s.Students {
        if item.RollNo == no {
            return item
        }
    }
    return nil
}
 
func (s *StudentBO) UpdateStudent(student *StudentVO) {
    prev := s.GetStudent(student.RollNo)
    prev.SetName(student.Name)
    fmt.Println("Update student No: ", prev.RollNo, " name to ", prev.Name)
}
 
func main() {
    studentBO := NewStudentBO()
    for _, item := range studentBO.GetAllStudents() {
        fmt.Println("=======")
        fmt.Println("student NO: ", item.RollNo, ", name: ", item.Name)
    }
    fmt.Println("=======")
 
    student := studentBO.GetAllStudents()[0]
    student.SetName("Michael")
    studentBO.UpdateStudent(student)
 
    student = studentBO.GetStudent(student.RollNo)
    fmt.Println("student NO: ", student.RollNo, ", name: ", student.Name)
}
Mahipalpur Escorts 说:
4 年前

This is such a great resource that you are providing and you give it away for free. I love seeing blogs that understand the value of providing a quality resource for free.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter