+1

Design Patterns - Builder Pattern

Định nghĩa

Builder Pattern là một pattern thuộc nhóm khởi tạo (creation patterns) cho phép tạo ra đối tượng với nhiều thể hiện khác nhau, giúp cho quá trình khởi tạo đối tượng đơn giản hơn.

Ưu điểm

  • Cung cấp thêm một cách khởi tạo đối tượng
  • Hỗ trợ, loại bớt việc phải viết nhiều constructor

Hạn chế

  • Phải tạo builder cho từng class khác nhau.

Ví dụ

Giả sử bạn cần xây dựng một văn phòng làm việc (Office) thì chúng ta cần khai báo:

public class Office {

    private int mCountTable;
    private int mCountChair;
    private int mCountLight;
    private int mCountAir;
    private int mCountFan;

    private Office(Builder builder) {
        mCountTable = builder.mCountTable;
        mCountChair = builder.mCountChair;
        mCountLight = builder.mCountLight;
        mCountAir = builder.mCountAir;
        mCountFan = builder.mCountFan;
    }

    public static class Builder {

        private int mCountTable;
        private int mCountChair;
        private int mCountLight;
        private int mCountAir;
        private int mCountFan;

        public Builder() {

        }

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

        public Builder setTable(int countTable) {
            this.mCountTable = countTable;
            return this;
        }

        public Builder setChair(int countChair) {
            this.mCountChair = countChair;
            return this;
        }

        public Builder setLight(int countLight) {
            this.mCountLight = countLight;
            return this;
        }

        public Builder setAir(int countAir) {
            this.mCountAir = countAir;
            return this;
        }

        public Builder setFan(int countFan) {
            this.mCountFan = countFan;
            return this;
        }

    }
}

Có thể khởi tạo 1 đối tượng Office bằng cách:

    Office.Builder builder = new Office.Builder();
    Office office = builder.setAir(20)
                            .setChair(30)
                            .build();

Lời kết

Việc áp dụng Builder Pattern sẽ giúp chúng ta có thể tạo ra đối tượng với một số hoặc tất cả các thuộc tính theo mong muốn một cách tiện lợi hơn.

Thao khảo:

http://ktmt.github.io/blog/2013/06/14/design-pattern-ap-dung-builder-pattern-trong-test-java


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí