-
Notifications
You must be signed in to change notification settings - Fork 246
/
composite.go
78 lines (65 loc) · 1.56 KB
/
composite.go
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
// Package composite is an example of the Composite Pattern.
package composite
// Component provides an interface for branches and leaves of a tree.
type Component interface {
Add(child Component)
Name() string
Child() []Component
Print(prefix string) string
}
// Directory implements branches of a tree
type Directory struct {
name string
childs []Component
}
// Add appends an element to the tree branch.
func (d *Directory) Add(child Component) {
d.childs = append(d.childs, child)
}
// Name returns name of the Component.
func (d *Directory) Name() string {
return d.name
}
// Child returns child elements.
func (d *Directory) Child() []Component {
return d.childs
}
// Print returns the branche in string representation.
func (d *Directory) Print(prefix string) string {
result := prefix + "/" + d.Name() + "\n"
for _, val := range d.Child() {
result += val.Print(prefix + "/" + d.Name())
}
return result
}
// File implements a leaves of a tree
type File struct {
name string
}
// Add implementation.
func (f *File) Add(child Component) {
}
// Name returns name of the Component.
func (f *File) Name() string {
return f.name
}
// Child implementation.
func (f *File) Child() []Component {
return []Component{}
}
// Print returns the leave in string representation.
func (f *File) Print(prefix string) string {
return prefix + "/" + f.Name() + "\n"
}
// NewDirectory is constructor.
func NewDirectory(name string) *Directory {
return &Directory{
name: name,
}
}
// NewFile is constructor.
func NewFile(name string) *File {
return &File{
name: name,
}
}