'자바 빌더 패턴'에 해당되는 글 1건

- 빌더패턴(Builder Pattern)

(# github 예제 소스 : https://github.com/HelloPlutoKid/JAVADesignPattern/tree/master/2.Builder)

 

정의 : 복합 객체의 생성 과정과 표현 방법을 분리하여 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있게 하는 패턴

(#위키 백과 : https://ko.wikipedia.org/wiki/%EB%B9%8C%EB%8D%94_%ED%8C%A8%ED%84%B4  

 

빌더 패턴을 사용하면, 생성자를 통한 변수 초기화를 빌더 패턴을 대신함으로써 여러 생성자를 생성할 필요가 없고, 생성자의 순서에 맞게 변수 내용을 작성할 필요성이 없습니다. 또한, 변수의 내용을 보다 직관적으로 초기화가 가능합니다.


빌더 패턴을 통한 음식을 만들어 보겠습니다.

 

Food와 FoodBuilder의 관계

     Food을 생성을 FoodBuider를 통해서 Food 객체 생성과 변수 초기화를 진행합니다.       

 

클래스 구조


1. Food.java

package food;

/**
 *  국수 음식 
 */
public class Food {
    private String source;
    private String meat;
    private String noodle;

    public Food(String source, String meat, String noodle){
        this.source = source;
        this.meat = meat;
        this.noodle = noodle;
    }

    /**
     * @param meat the meat to set
     */
    public void setMeat(String meat) {
        this.meat = meat;
    }

    /**
     * @param noodle the noodle to set
     */
    public void setNoodle(String noodle) {
        this.noodle = noodle;
    }

    /**
     * @param source the source to set
     */
    public void setSource(String source) {
        this.source = source;
    }

    /**
     * @return the meat
     */
    public String getMeat() {
        return meat;
    }
    
    /**
     * @return the noodle
     */
    public String getNoodle() {
        return noodle;
    }

    /**
     * @return the source
     */
    public String getSource() {
        return source;
    }

    @Override
    public String toString() {
        return "source = >" + source + "," + "noodle = >" + noodle + "," + "meat = >" + meat;
    }
    
}

2. FoodBuilder.java

package food;

public class FoodBuilder {
    private Food food;

    public FoodBuilder(){
        food = new Food("","","");
    }

    public FoodBuilder start(){
        return this;
    }
    public FoodBuilder setSource(String source){
        this.food.setSource(source);
        return this;
    }

    public FoodBuilder setMeat(String meat){
        this.food.setMeat(meat);
        return this;
    }

    public FoodBuilder setNoodle(String noodle){
        this.food.setNoodle(noodle);
        return this;
    }

    public Food build(){
        return this.food;
    }
}

 

 

 


3. Main.java

import food.Food;
import food.FoodBuilder;

/**
 * Main
 */
public class Main {

    public static void main(String[] args) {
    	// 모든 변수를 초기화 하는 경우 
        Food food1 = new FoodBuilder()
        		.start()
        		.setSource("라면스프")
        		.setNoodle("라면사리")
        		.setMeat("소고기")
        		.build();
        
        // meat를 제외한 변수를 초기화 하는 경우 
        Food food2 = new FoodBuilder()
        		.start()
        		.setSource("쌀스프")
        		.setNoodle("국수")
        		.build();

        System.out.println(food1.toString());
        System.out.println(food2.toString());

    }
}

4. 결과화면

 

블로그 이미지

미나미나미

,