forked from tugul/CoreJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImmutableObject.java
More file actions
45 lines (37 loc) · 1.13 KB
/
Copy pathImmutableObject.java
File metadata and controls
45 lines (37 loc) · 1.13 KB
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
package designpatterns;
import java.util.*;
/**
* Immutable object pattern:
* - creational pattern ensures object's state doesn't change after created
* - provides thread safety
*
* Common behaviour:
* - final class or its methods are final to prevent being overridden
* - has no setter to modify, so thread-safe
* - its constructor sets all variables on its creation
* - all instance variables are private final
* - has no reference to mutable objects to be accessed directly
* - don't use directly mutable object parameter, instead use of its copy
*
*/
final class Computer {
private final int memory;
private final String name;
private List<String> components;
public Computer(int memory, String name, List<String> components) {
this.memory = memory;
this.name = name;
this.components = new ArrayList<>(components); // make copy of mutable object
}
public int getMemory() {
return memory;
}
public String getName() {
return name;
}
public List<String> getComponents() {
return new ArrayList<>(components);
}
}
public class ImmutableObject {
}