public abstract class Troops { protected String leader; protected ArrayList<String> others = new ArrayList<>(); protected String purpose; //领袖 public void setLeader(String leader) { this.leader = leader; } //其他人 public void setOthers(String... others) { for (String other:others){ this.others.add(other); } } //宗旨 public abstract void setPurpose(); @Override public String toString() { return "Troops{" + "leader=‘" + leader + ‘\‘‘ + ", others=" + others.toString() + ", purpose=‘" + purpose + ‘\‘‘ + ‘}‘; } }
这是梁山的Troops:
public class Liangshan extends Troops { protected Liangshan(){} @Override public void setPurpose() { purpose = "替天行道"; } }
再写一个Builder:
public abstract class Builder { public abstract void buildLeader(String leader); public abstract void buildOthers(String... others); public abstract void buildPurpose(); public abstract Troops create(); }
这是好汉们的Builder:
public class LiangshanBuilder extends Builder { private Liangshan liangshan; @Override public void buildLeader(String leader) { liangshan.setLeader(leader); } @Override public void buildOthers(String... others) { liangshan.setOthers(others); } @Override public void buildPurpose() { liangshan.setPurpose(); } @Override public Troops create() { return liangshan; } }
接下来写一个Director:
public class Director { Builder mBuilder = null; public Director(Builder builder){ this.mBuilder = builder; } public void construct(String leader,String... others){ mBuilder.buildLeader(leader); mBuilder.buildOthers(others); mBuilder.buildPurpose(); } }
我们只需要如下代码便可以实现梁山好汉的大聚义:
Builder builder = new LiangshanBuilder(); Director director = new Director(builder); director.construct("宋江","卢俊义","吴用","公孙胜"); Log.e("梁山",builder.create().toString());