设计模式-建造者模式
定义:属于创建型模式,提供了一种创建对象的方式,一个 Builder 类会一步一步使用简单对象构造出最终的复杂对象,这个Builder 类是独立于其他对象的
角色:产品(Ailoy())、抽象建造者(Builder())、建造者(BuilderA()、BuilderB()、NumA()、NumB())、指挥者(Scientist())
目标:将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示
优点:封装性好,扩展性好,各个具体的建造者相互独立,有利于系统的解耦
建造者可以对创建过程逐步细化,而不对其它模块产生任何影响,便于控制细节风险
缺点:产品必须有共同点,范围有限制
内部变化复杂,会有很多的建造类
实现:
//产品 public class Alloy { private String name; private List<String> stuff; private int num; public void setName(String name) { this.name = name; } public void setStuff(List<String> stuff) { this.stuff = stuff; } public void setNum(int num) { this.num = num; } public String show(){ StringBuffer stringBuffer = new StringBuffer(); for (String st: stuff) { stringBuffer.append(st); stringBuffer.append("||"); } return this.name+"&&"+stringBuffer.toString()+"&&"+this.num; } } //抽象建造者 public abstract class Builder { Alloy alloy = new Alloy(); public abstract void buildName(); public abstract void buildStuff(); public abstract void buildNum(); public Alloy resultAlloy( ){ return alloy; } } //具体建造者A public class BuilderA extends Builder{ @Override public void buildName() { alloy.setName("钠铁合金"); } @Override public void buildStuff() { List<String> list = new ArrayList<String>(); list.add("Fe"); list.add("Na"); alloy.setStuff(list); } @Override public void buildNum() { alloy.setNum(new NumA().num()); } } //具体建造者B public class BuilderB extends Builder { @Override public void buildName() { alloy.setName("铝镁合金"); } @Override public void buildStuff() { List<String> list = new ArrayList<String>(); list.add("Mg"); list.add("Al"); alloy.setStuff(list); } @Override public void buildNum() { alloy.setNum(new NumB().num()); } } //具体建造者C public class NumA { public int num(){ return 5; } } //具体建造者D public class NumB { public int num(){ return 10; } } //指挥者 public class Scientist { private Builder builder; public Scientist (Builder builder){ this.builder = builder; } public Alloy study(){ builder.buildName(); builder.buildStuff(); builder.buildNum(); return builder.resultAlloy(); } } //测试方法 public class Test { public static void main(String[] args) { Builder builder = new BuilderA(); Scientist scientist = new Scientist(builder); Alloy alloy = scientist.study(); System.out.println(alloy.show()); } } //测试结果 钠铁合金&&Fe||Na||&&5