31bfc28b-7658-44c0-93d2-3a24e63a1c57.webp

Builder Pattern là một thiết kế mẫu (design pattern) trong lập trình hướng đối tượng giúp tạo ra các đối tượng phức tạp một cách có hệ thống và dễ hiểu. Nó tách biệt quá trình xây dựng một đối tượng khỏi biểu diễn của nó, cho phép cùng một quá trình xây dựng có thể tạo ra các biểu diễn khác nhau.

Khi nào nên sử dụng Builder Pattern?

VD:

e8911942-ef10-4353-a1a3-d54c48596425.webp

Nhược điểm

Ví dụ về Builder Pattern

Giả sử chúng ta có một lớp House với nhiều thuộc tính khác nhau như số tầng, số phòng, có bể bơi hay không, có gara hay không. Chúng ta sẽ sử dụng Builder Pattern để tạo đối tượng House.

Untitled

Vậy thì xem code cho dễ hiểu nha:

Lớp House với Builder Pattern

public class House {
    private final int floors;
    private final int rooms;
    private final boolean hasSwimmingPool;
    private final boolean hasGarage;

    private House(HouseBuilder builder) {
        this.floors = builder.floors;
        this.rooms = builder.rooms;
        this.hasSwimmingPool = builder.hasSwimmingPool;
        this.hasGarage = builder.hasGarage;
    }

    public static class HouseBuilder {
        private int floors;
        private int rooms;
        private boolean hasSwimmingPool;
        private boolean hasGarage;

        public HouseBuilder setFloors(int floors) {
            this.floors = floors;
            return this;
        }

        public HouseBuilder setRooms(int rooms) {
            this.rooms = rooms;
            return this;
        }

        public HouseBuilder setHasSwimmingPool(boolean hasSwimmingPool) {
            this.hasSwimmingPool = hasSwimmingPool;
            return this;
        }

        public HouseBuilder setHasGarage(boolean hasGarage) {
            this.hasGarage = hasGarage;
            return this;
        }

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

    @Override
    public String toString() {
        return "House{" +
                "floors=" + floors +
                ", rooms=" + rooms +
                ", hasSwimmingPool=" + hasSwimmingPool +
                ", hasGarage=" + hasGarage +
                '}';
    }
}

Sử dụng

public class Main {
    public static void main(String[] args) {
        House house = new House.HouseBuilder()
                .setFloors(2)
                .setRooms(4)
                .setHasSwimmingPool(true)
                .setHasGarage(true)
                .build();
    }
}