티스토리 뷰

데이터 객체를 생성할 때 사용하는 from, of, builder 패턴을 비교해 보겠습니다.

 

  • of: 엔티티의 필수 데이터를 이용하여 객체를 생성할 때 사용
    • 객체 생성에 필요한 필수 인자가 명확하고, 불변 객체를 만들거나 간단한 유효성 검사를 수행하고 싶을 때 유용합니다.
public static User of(String username, String email) { // 필수 필드
    return new User(null, username, email);
}

public static Color of(int red, int green, int blue) {
    return new Color(red, green, blue);
}

 

  • from: 다른 객체로부터 객체를 생성할 때 주로 사용
    • 다른 객체나 데이터 구조로부터 엔티티 객체를 생성하거나 매핑하는 로직을 명확하게 분리하고 싶을 때 사용합니다.
public static User from(UserDto userDto) {
    return new User(null, userDto.getUsername(), userDto.getEmail());
}

public static Order from(ResultSet rs) throws SQLException {
    return new Order(rs.getLong("id"), rs.getString("orderNumber"), ...);
}

 

  • builder: 속성이 많은 객체를 단계별로 생성할 때 사용
    • 생성해야 할 객체의 속성이 많거나 선택적인 속성이 많아 생성자의 파라미터가 늘어나는 것을 방지하고, 객체 생성 과정을 더 명확하고 유연하게 관리하고 싶을 때 사용합니다.
public class Computer {
    private String cpu;
    private String ram;
    private String storage;
    private String graphicsCard; // 선택적

    private Computer(Builder builder) {
        this.cpu = builder.cpu;
        this.ram = builder.ram;
        this.storage = builder.storage;
        this.graphicsCard = builder.graphicsCard;
    }

    public static class Builder {
        private String cpu;
        private String ram;
        private String storage;
        private String graphicsCard;

        public Builder(String cpu, String ram, String storage) { // 필수 필드
            this.cpu = cpu;
            this.ram = ram;
            this.storage = storage;
        }

        public Builder graphicsCard(String graphicsCard) { // 선택적 필드
            this.graphicsCard = graphicsCard;
            return this;
        }

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

    // Getter 생략

    public static void main(String[] args) {
        Computer myComputer = new Computer.Builder("Intel i7", "16GB", "512GB SSD")
                .graphicsCard("NVIDIA RTX 3060")
                .build();

        Computer basicComputer = new Computer.Builder("Intel i5", "8GB", "256GB HDD")
                .build();
    }
}

 

 

반응형

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

[java][디자인패턴] Template Method 패턴  (0) 2018.02.27
[java][디자인패턴] Adapter 패턴  (0) 2018.02.26
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/05   »
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
글 보관함