๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Java/Java ์ด๋ก 

Builder ํŒจํ„ด (Java)

Builder ํŒจํ„ด

์ƒ์„ฑ์ž์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•ด ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค ๋•Œ Builder ํŒจํ„ด์„ ์‚ฌ์šฉํ•œ๋‹ค.

ํ•„์š”์„ฑ

์ƒ์„ฑ์ž์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•ด ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค ๋•Œ, ์‹ ๊ฒฝ ์จ์•ผ ํ•  ์ธ์ž๋“ค์ด 2~3๊ฐœ๋ผ๋ฉด ์ƒ๊ด€์—†์ง€๋งŒ ์ธ์ž๋“ค์ด 20๊ฐœ, 30๊ฐœ .. ๋งŽ์€ ์ˆ˜๋ผ๊ณ  ์ƒ๊ฐํ•ด๋ณด์ž.

๊ทธ๋•Œ๊ทธ๋•Œ ์ƒํ™ฉ์— ๋งž๋Š” ์ƒ์„ฑ์ž๋ฅผ ์ผ์ผ์ด ๋งŒ๋“ค์–ด ์ค„ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— Builder Pattern์„ ์ด์šฉํ•œ๋‹ค.

์˜ˆ์ œ

public class Test {
    private int testEl1;
    private int testEl2;
    private int testEl3;
    private int testEl4;
    private int testEl5;
}

์œ„์™€ ๊ฐ™์€ Test Class๊ฐ€ ์žˆ๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ณด์ž.

์›ํ•˜๋Š” ๊ทธ๋•Œ๊ทธ๋•Œ ์›ํ•˜๋Š” ๋ณ€์ˆ˜๋งŒ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋Š” ์ƒ์„ฑ์ž๋ฅผ ๋งŒ๋“ค๊ธฐ ํž˜๋“ค๋‹ค.

์ด๋•Œ builder parttern์„ ์‚ฌ์šฉํ•œ๋‹ค.

public class Test {
    private int testEl1;
    private int testEl2;
    private int testEl3;
    private int testEl4;
    private int testEl5;

    public static class Builder {
        private final int testEl1;
        private final int testEl2;
        private int testEl3 = 0;
        private int testEl4 = 0;
        private int testEl5 = 0;

        public Builder(int testEl1, int testEl2){
            this.testEl1 = testEl1;
            this.testEl2 = testEl2;
        }

        public Builder testEl3(int testEl3){
            this.testEl3 = testEl3;
            return this;
        }

        public Builder testEl4(int testEl4){
            this.testEl4 = testEl4;
            return this;
        }

        public Builder testEl5(int testEl5){
            this.testEl5 = testEl5;
            return this;
        }

        public Test build() {
            return new Test(this);
        }
    }
    private Test(Builder builder){
        testEl1 = builder.testEl1;
        testEl2 = builder.testEl2;
        testEl3 = builder.testEl3;
        testEl4 = builder.testEl4;
        testEl5 = builder.testEl5;
    }
}

testEl1, testEl2 ๋Š” ํ•„์ˆ˜๋กœ ๊ฐ’์„ ์ง€์ •ํ•ด์„œ ์ƒ์„ฑํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๊ณ , ๋‚˜๋จธ์ง€ ์ธ์ž๋“ค์€ default ๊ฐ’์„ ์ •ํ•ด์ฃผ๊ณ  ํ•„์š”ํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.

Test ํด๋ž˜์Šค ์•ˆ์— ๋‚ด๋ถ€์ ์œผ๋กœ Builder ๋ฉ”์„œ๋“œ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ๊ณ , return์„ ํ™œ์šฉํ•ด ์ˆœ์ฐจ์ ์œผ๋กœ ๋ฉ”์„œ๋“œ๋ฅผ ๋ถˆ๋Ÿฌ์„œ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

    public static void main(String[] args){
        Test test = new Builder(1,0).testEl3(5).testEl5(10).build();
    }

์œ„์™€ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•„์ˆ˜์ ์œผ๋กœ ๋“ค์–ด๊ฐ€์•ผ ํ•  ์ธ์ž์™€ ๋‚˜๋จธ์ง€๋Š” ์„ ํƒ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜์—ฌ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

์›น์—์„œ ์‚ฌ์šฉ

์›น์—์„œ๋Š” ํŠน์ • ํด๋ž˜์Šค์— ๋งน๋ชฉ์ ์œผ๋กœ Setter๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋””์„œ ๊ฐ’์ด ๋ณ€ํ–ˆ๋Š”์ง€ ์•Œ ์ˆ˜ ์—†๊ณ  ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค.

์ด๋Ÿฌํ•œ ๋ฌธ์ œ๋ฅผ Builder Pattern์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๊ณ , ์Šคํ”„๋ง์˜ ๊ฒฝ์šฐ Lombok์„ ํ™œ์šฉํ•˜๋ฉด ์–ด๋…ธํ…Œ์ด์…˜ ํ•˜๋‚˜๋กœ Builder๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.