以建造一个三角形圆形矩形的图形为例
- public class Shape {
- private String triangle;
- private String circular;
- private String rectangle;
-
- public void setTriangle(String triangle) {
- this.triangle = triangle;
- }
-
- public void setCircular(String circular) {
- this.circular = circular;
- }
-
- public void setRectangle(String rectangle) {
- this.rectangle = rectangle;
- }
-
- public void draw() {
- //使用得到的具体的三角形圆形矩形绘制一个图形
- }
- }
- abstract class Builder {
- protected Shape shape = new Shape();
- public abstract void buildTriangle();
- public abstract void buildCircular();
- public abstract void buildRectangle();
-
- public Shape getShape() {
- return shape;
- }
- }
- public class ConcreteBuilder1 extends Builder{
- @Override
- public void buildTriangle() {
- shape.setTriangle("建造 红色三角形");
- }
-
- @Override
- public void buildCircular() {
- shape.setCircular("建造 蓝色圆形");
- }
-
- @Override
- public void buildRectangle() {
- shape.setRectangle("建造 绿色矩形");
- }
- }
- public class ConcreteBuilder2 extends Builder{
- @Override
- public void buildTriangle() {
- shape.setTriangle("建造 青色三角形");
- }
-
- @Override
- public void buildCircular() {
- shape.setCircular("建造 蓝色圆形");
- }
-
- @Override
- public void buildRectangle() {
- shape.setRectangle("建造 紫色矩形");
- }
- }
- public class Director {
- private Builder builder;
- public Director(Builder builder) {
- this.builder = builder;
- }
- //产品构建与组装方法
- public Shape construct() {
- builder.buildTriangle();
- builder.buildCircular();
- builder.buildRectangle();
- return builder.getShape();
- }
- }
- public static void main(String[] args) {
-
- Builder builder = new ConcreteBuilder1();
- Director director = new Director(builder);
- Shape shape = director.construct();
- shape.draw();
-
- builder = new ConcreteBuilder2();
- director = new Director(builder);
- shape = director.construct();
- shape.draw();
- }