BuilderPattern建造者模式

建造者模式

1.定義

將一個複雜對象的構建與它的表示分離,使得一樣的構建過程能夠建立不一樣的表示。java

建造者模式一般有4個角色ide

Person抽象類:定義模板方法及基本方法函數

public abstract class AbstractPerson {

    private boolean canSwim = true;

    public void setCanSwim(boolean canSwim) {
        this.canSwim = canSwim;
    }

    protected abstract void walk();

    protected abstract void run();

    protected abstract void swim();

    public final void exercises() {
        this.walk();

        if (this.canSwim()) {
            this.swim();
        }

        this.run();
    }

    protected boolean canSwim() {
        return canSwim;
    }
}

Person實現類:實現基本方法,一般實現模板方法模式,有模板方法及基本方法ui

public class PersonA extends AbstractPerson {

    @Override
    protected void walk() {
        System.out.println("person a walk");
    }

    @Override
    protected void run() {
        System.out.println("person a run");
    }

    @Override
    protected void swim() {
        System.out.println("person a swim");
    }
}

public class PersonB extends AbstractPerson {

    @Override
    protected void walk() {
        System.out.println("person b walk");
    }

    @Override
    protected void run() {
        System.out.println("person b run");
    }

    @Override
    protected void swim() {
        System.out.println("person b swim");

    }
}

Builder抽象建造者:規範Person行爲,設置Person的組建,通常由子類實現this

public abstract class AbstractBuilder {

    public abstract void setPart();

    public abstract AbstractPerson builderPerson();
}

Builder實現類:具體的建造者code

public class PersonABuilder extends AbstractBuilder {

    private AbstractPerson person = new PersonA();

    @Override
    public void setPart() {
        person.setCanSwim(true);
    }

    @Override
    public AbstractPerson builderPerson() {
        return person;
    }
}

public class PersonBBuilder extends AbstractBuilder {

    private AbstractPerson person = new PersonB();

    @Override
    public void setPart() {
        person.setCanSwim(false);
    }

    @Override
    public AbstractPerson builderPerson() {
        return person;
    }
}

Director導演類對象

public class Director {

    private AbstractBuilder personABuilder = new PersonABuilder();

    private AbstractBuilder personBBuilder = new PersonBBuilder();

    public PersonA getPersonA() {
        this.personABuilder.setPart();
        return (PersonA) this.personABuilder.builderPerson();
    }

    public PersonB getPersonB() {
        this.personBBuilder.setPart();
        return (PersonB) this.personBBuilder.builderPerson();
    }
}

注意:建造者模式關注的是產品的類型(setPart函數)與產品裝配的順序(exercises函數)ci

2.應用

2.1 優勢

  • 封裝性:建造者模式,能夠沒必要知道產品(Person)內部的組成細節及實現
  • 建造者獨立容易擴展
  • 方便控制生產的細節:能夠對建造過程(builderPerson函數)逐步細化,而不會對其它模塊產生影響

2.2 使用場景

  • 相同的方法,不一樣的執行順序,產生不一樣的結果
  • 同一個對象能夠裝配不一樣的部件(setPart函數),產生的運行結果也不相同
  • 對象建立過程當中依賴系統的其它對象,且這些被依賴的對象不易被獲得
相關文章
相關標籤/搜索