1 class Product 2 { 3 @Override 4 public String toString() { 5 return "Product"; 6 } 7 } 8 9 interface Builder 10 { 11 void BuildPart(); 12 } 13 14 class ConcreteBuilder implements Builder 15 { 16 17 @Override 18 public void BuildPart() { 19 // TODO Auto-generated method stub 20 System.out.println("Building Product's part"); 21 } 22 23 public Product GetResult() 24 { 25 System.out.println("Product's Building has finished"); 26 return new Product(); 27 28 } 29 } 30 31 class Director 32 { 33 public Product Construct(ConcreteBuilder cb) 34 { 35 cb.BuildPart(); 36 return cb.GetResult(); 37 } 38 } 39 40 public class TestModelBuilder { 41 42 /** 43 * @param args 44 */ 45 public static void main(String[] args) { 46 // TODO Auto-generated method stub 47 Director d=new Director(); 48 ConcreteBuilder cb=new ConcreteBuilder(); 49 Product p=d.Construct(cb); 50 System.out.println(p); 51 } 52 }
例子
1 class Car{ 2 3 @Override 4 public String toString() { 5 return "汽车产品"; 6 } 7 } 8 9 interface IBuilder 10 { 11 void BuildWheel(); 12 void BuildCarFrame(); 13 void BuildEngine(); 14 } 15 16 class CarBuilder implements IBuilder 17 { 18 19 private Car car=new Car(); 20 @Override 21 public void BuildCarFrame() { 22 // TODO Auto-generated method stub 23 System.out.println("建造汽车框架"); 24 } 25 26 @Override 27 public void BuildEngine() { 28 // TODO Auto-generated method stub 29 System.out.println("建造汽车轮子"); 30 } 31 32 @Override 33 public void BuildWheel() { 34 // TODO Auto-generated method stub 35 System.out.println("建造汽车引擎"); 36 } 37 38 public Car CarBuildOver() 39 { 40 System.out.println("汽车组装完毕"); 41 return car; 42 } 43 } 44 45 class CarDirector 46 { 47 48 public Car BuildCar(CarBuilder cb) 49 { 50 cb.BuildCarFrame(); 51 cb.BuildEngine(); 52 cb.BuildWheel(); 53 return cb.CarBuildOver(); 54 } 55 } 56 57 public class TestModelBuilder_1 { 58 59 /** 60 * @param args 61 */ 62 public static void main(String[] args) { 63 // TODO Auto-generated method stub 64 CarDirector cd=new CarDirector(); 65 Car c=cd.BuildCar(new CarBuilder()); 66 System.out.println(c); 67 } 68 }