design pattern

build

  • java
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
//Computer

public class Computer {

//required parameters
private String HDD;
private String RAM;

//optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;


public String getHDD() {
return HDD;
}

public String getRAM() {
return RAM;
}

public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}

public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}

private Computer(ComputerBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}

//Builder Class
public static class ComputerBuilder{

// required parameters
private String HDD;
private String RAM;

// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;

public ComputerBuilder(String hdd, String ram){
this.HDD=hdd;
this.RAM=ram;
}

public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}

public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}

public Computer build(){
return new Computer(this);
}

}

//ComputerBuilder

import com.journaldev.design.builder.Computer;

public class TestBuilderPattern {

public static void main(String[] args) {
//Using builder to get the object in a single line of code and
//without any inconsistent state or arguments management issues
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
}