设计模式四(建造者模式)

NightRain.png

定义

将一个复杂对象的构建与它的表示分离,同样的构建过程可以创建不同的表示

使用场景

  • 复杂的产品类
  • 多样性的功能

示例

Director(产品类)

public class PhoneProduct {
    private String system;
    private String cpu;
    private String ram;
    private String rom;

    public void setSystem(String system) {
        this.system = system;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public void setRam(String ram) {
        this.ram = ram;
    }

    public void setRom(String rom) {
        this.rom = rom;
    }

    @NonNull
    @Override
    public String toString() {
        return "\n系统:" + system + "\nCUP:" + cpu + "\n运存:" + ram + "\n内部储存:" + rom;
    }
}

IBuilder(抽象建造者)

public interface IBuilderPhone {
    void buildSystem(String system);

    void buildCup(String cup);

    void buildRam(String ram);

    void buildRom(String rom);

    PhoneProduct build();
}

Builder(具体建造者)

public class BuilderPhone implements IBuilderPhone {
    private PhoneProduct mPhoneProduct = new PhoneProduct();


    @Override
    public void buildSystem(String system) {
        mPhoneProduct.setSystem(system);
    }

    @Override
    public void buildCup(String cpu) {
        mPhoneProduct.setCpu(cpu);
    }

    @Override
    public void buildRam(String ram) {
        mPhoneProduct.setRam(ram);
    }

    @Override
    public void buildRom(String rom) {
        mPhoneProduct.setRom(rom);
    }

    @Override
    public PhoneProduct build() {
        return mPhoneProduct;
    }
}

Director(导演类)

public class DirectorPhone {
    private IBuilderPhone mIBuilderPhone;

    public DirectorPhone(IBuilderPhone mIBuilderPhone) {
        this.mIBuilderPhone = mIBuilderPhone;
    }

    public PhoneProduct createPhone(String system, String cpu, String ram, String rom) {
        mIBuilderPhone.buildSystem(system);
        mIBuilderPhone.buildCup(cpu);
        mIBuilderPhone.buildRam(ram);
        mIBuilderPhone.buildRom(rom);
        return mIBuilderPhone.build();
    }
}

使用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PhoneProduct mPhoneProduct = new DirectorPhone(new BuilderPhone()).createPhone("EMUI", "麒麟", "4G", "16G");
        Log.i(TAG, "onCreate: "+mPhoneProduct.toString());
    }
Result.png

你可能感兴趣的:(设计模式四(建造者模式))