首页 > 其他 > 详细

设计模式(建造者)

时间:2015-06-12 14:46:17      阅读:145      评论:0      收藏:0      [点我收藏+]

建造者模式用于创建相对复杂,组成较多的对象。它包括几类角色:

  • Product: 待被创建的对象,本例中是Table
  • builder:创建对象方法的抽象,本例中是TableBuilder
  • ConcreteBuilder:具体某个创建的实现,本例中是TableBuilderImpl
  • Director:封装builder接口

类图关系如下:

技术分享

代码如下:

  • Table
package com.example;

public class Table {
    private String head;
    private String content;
    private String footer;
    
    public String getHead() {
        return head;
    }
    public void setHead(String head) {
        this.head = head;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getFooter() {
        return footer;
    }
    public void setFooter(String footer) {
        this.footer = footer;
    }
    
    public String getTable(){
        return this.head + "_" + this.content + "_" + this.footer;
    }
}
  • TableBuilder
public interface TableBuilder {
    public TableBuilder setTableHead(String head);
    public TableBuilder setTableContent(String content);
    public TableBuilder setTableFooter(String footer);
    public Table builder();
}
  • TableBuilderImpl
package com.example;

public class TableBuilderImpl implements TableBuilder {
    
    private Table table;
    private static final String TYPE = "TYPE1";
    
    public TableBuilderImpl(){
        table = new Table();
    }

    @Override
    public TableBuilder setTableHead(String head) {
        table.setHead(TYPE + head);
        return this;    
    }

    @Override
    public TableBuilder setTableContent(String content) {
        table.setContent(TYPE + content);
        return this;
    }

    @Override
    public TableBuilder setTableFooter(String footer) {
        table.setFooter(TYPE + footer);
        return this;
    }

    @Override
    public Table builder() {
        return table;
    }
}
  • Director
public class Director {
    private TableBuilder builder;
    
    public Director(TableBuilder builder){
        this.builder = builder;
    }
    
    public Table Builder(){
        return builder.setTableHead("head")
                .setTableContent("content")
                .setTableFooter("footer")
                .builder();
    }
}
  • APP
public class App {

    public static void main(String[] args) {
        Director direct = new Director(new TableBuilderImpl());
        Table table = direct.Builder();
        System.out.println(table.getTable());
    }
}

设计模式(建造者)

原文:http://www.cnblogs.com/Fredric-2013/p/4571573.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!