본문 바로가기

IT/디자인 패턴

Builder Design Pattern

반응형

When instantiating a class in client program, passing many arguments to a constructor can cause errors in many situations and bothersome. ex. having to remember constructor's parameter sequence. 

 

Builder design pattern solves this issue by building step by step, allowing client to designate only needed variables. 

 

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
package creational.builder;
 
public class Phone {
    
    private int gb;
    private int ram;
    private boolean graphicsCardEnabled;
    
    
    
    public Phone(PhoneBuilder builder) {
        super();
        this.gb = builder.gb;
        this.ram = builder.ram;
        this.graphicsCardEnabled = builder.graphicsCardEnabled;
    }
    
    public int getGb() {
        return gb;
    }
    public int getRam() {
        return ram;
    }
    public boolean isGraphicsCardEnabled() {
        return graphicsCardEnabled;
    }
    
    @Override
    public String toString() {
        return "Phone [gb=" + gb + ", ram=" + ram + ", graphicsCardEnabled=" + graphicsCardEnabled + "]";
    }
 
    public static class PhoneBuilder{
        
        private int gb;
        private int ram;
        private boolean graphicsCardEnabled;
        
        
        public PhoneBuilder(int gb) {
            super();
            this.gb = gb;
        }
        
        public PhoneBuilder setGb(int gb) {
            this.gb = gb;
            return this;
        }
        public PhoneBuilder setRam(int ram) {
            this.ram = ram;
            return this;
        }
        public PhoneBuilder setGraphicsCardEnabled(boolean graphicsCardEnabled) {
            this.graphicsCardEnabled = graphicsCardEnabled;
            return this;
        }
        
        public Phone build() {
            return new Phone(this);
        }
        
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
public class MainClass {
 
    public static void main(String[] args) {
        Phone phone = new PhoneBuilder(2).setGraphicsCardEnabled(true).build();
        System.out.println(phone);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

 

반응형

'IT > 디자인 패턴' 카테고리의 다른 글

Strategy Pattern  (0) 2020.02.28
Abstract Factory Design Pattern  (0) 2020.02.24
Factory Design Pattern  (0) 2020.02.22
Singleton Pattern  (0) 2020.02.19