-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
77 lines (56 loc) · 1.42 KB
/
index.ts
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
abstract class Component {
protected parent: Component
public setParent(parent: Component) {
this.parent = parent
}
public getParent(): Component {
return this.parent
}
public add(component: Component): void { }
public remove(component: Component): void { }
public isComposite(): boolean {
return false
}
public abstract operation(): string
}
class Product extends Component {
public operation(): string {
return 'Product';
}
}
class Composite extends Component {
protected children: Component[] = [];
public add(component: Component): void {
this.children.push(component)
component.setParent(this)
}
public remove(component: Component): void {
const index = this.children.indexOf(component)
this.children.splice(index, 1)
component.setParent(null)
}
public isComposite(): boolean {
return true
}
public operation(): string {
const results = []
this.children.forEach((child: Component) => {
results.push(child.operation())
})
return `Box [${results.join(' + ')}]`
}
}
function clientCodeContext() {
const tree = new Composite()
const branchOne = new Composite()
branchOne.add(new Product())
branchOne.add(new Product())
const branchTwo = new Composite()
branchTwo.add(new Product())
tree.add(branchOne)
tree.add(branchTwo)
console.log(tree.operation());
}
export function composite() {
clientCodeContext()
}