Skip to content

Builder

Amir edited this page May 28, 2022 · 1 revision

الگو طراحی Builder


عضو گروه Creatinal
این پترن بیشتر زمانی مورد اهمیته که با کلاسای بزرگ و پیچیده سر و کار داریم. به عبارت ساده تر کمکمون میکنه که اشیاء با پیچیدگی زیاد، راحت تر و یا شاید با اشیاء ساده تر ساخته بشن.



builder





کاربردها

  1. امکان ساخت نمونه‌های مختلفی از یک شی را فراهم می‌سازد
  2. باعث جلوگیری از ساخت تعداد زیادی Constructor برای ساخت اشیا می‌شود
  3. ساخت اشیای پیچیده و مرکب را ساده‌تر می‌کند
  4. امکان ست کردن پارامترهای دلخواه برای شئ

معایب

  • بالا بردن حجم کد

مثال از ساخت یک شئ بدون استفاده از این دیزاین پترن

Home home = new Home(10, 15, 45, Red, Wood)

مثال از ساخت شئ با استفاده از builder

Home home = new Home.Builder()
                    .setDoorWidth(10)
                    .setWindowWidth(15)
                    .setArea(45)
                    .setDoorColor(Red)
                    .setWindowType(Wood)

ساختار کلاس قبل از اضافه کردن Builder

class Home {

    int doorWidth;
    int windowWidth;
    int area;
    String doorColor;
    String windowType;

    public Home(int doorWidth, int windowWidth, int area, String doorColor, String windowType) {
        this.doorWidth = doorWidth;
        this.windowWidth = windowWidth;
        this.area = area;
        this.doorColor = doorColor;
        this.windowType = windowType;
    }

}

روش پیاده‌سازی builder

final public class Home {

    public int doorWidth;
    public int windowWidth;
    public int area;
    public String doorColor;
    public String windowType;

    public Home(Builder builder) {
        this.doorWidth = builder.doorWidth;
        this.windowWidth = builder.windowWidth;
        this.area = builder.area;
        this.doorColor = builder.doorColor;
        this.windowType = builder.windowType;
    }

    public static class Builder{

        private int doorWidth;
        private int windowWidth;
        private int area;
        private String doorColor;
        private String windowType;

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

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

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

        public Builder setDoorColor(String doorColor) {
            this.doorColor = doorColor;
            return this;
        }

        public Builder setWindowType(String windowType) {
            this.windowType = windowType;
            return this;
        }

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

    }

}

Is necessary

Design Pattern

Creational

Structural

Behavioral

Template

Clone this wiki locally