将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示. 用户只需指定需要构建的类型,过程和细节不需知道.
1 2 3 4 5 6 7 8 9 10 11 package builder;public interface Builder { void hands () ; void legs () ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package builder;public class FatBuilder implements Builder { public void hands () { System.out.println("胖手" ); } public void legs () { System.out.println("胖腿" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package builder;public class ThinBuilder implements Builder { public void hands () { System.out.println("瘦手" ); } public void legs () { System.out.println("瘦腿" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package builder;public class Director { private Builder builder; public Director (Builder builder) { this .builder = builder; } public void build () { builder.hands(); builder.legs(); } public void setBuilder (Builder builder) { this .builder = builder; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package builder;public class Main { public static void main (String[] args) { Director director = new Director (new FatBuilder ()); director.build(); director.setBuilder(new ThinBuilder ()); director.build(); } }