mybatis学习::设计模式-builder模式1

学习设计模式,也是读码的一个乐趣。
从mybatis的基础代码,看看builder模式怎么玩

public class Environment {
  private String id;
  private TransactionFactory transactionFactory;
  private DataSource dataSource;

  public Environment(String id, TransactionFactory transactionFactory, DataSource dataSource) {
    this.id = id;
    this.transactionFactory = transactionFactory;
    this.dataSource = dataSource;
  }

  private Environment() {
  }

  public static class Builder {
    private Environment environment = new Environment();

    public Builder(String id, TransactionFactory transactionManager, DataSource dataSource) {
      environment.id = id;
      environment.transactionFactory = transactionManager;
      environment.dataSource = dataSource;
    }

    public Builder transactionFactory(TransactionFactory transactionFactory) {
      environment.transactionFactory = transactionFactory;
      return this;
    }

    public Builder dataSource(DataSource dataSource) {
      environment.dataSource = dataSource;
      return this;
    }

    public String id() {
      return environment.id;
    }

    public Environment build() {
      return environment;
    }

  }

  public String getId() {
    return id;
  }

  public TransactionFactory getTransactionFactory() {
    return transactionFactory;
  }

  public DataSource getDataSource() {
    return dataSource;
  }

}

小结

这种实现builder模式的要点:
1.被构建对象,构造函数私有化

private Environment() {
  }

2.public static 静态内部类

public static class Builder

3.大部分方法返回Builder本身,方便链式操作

Builder dataSource(xxx)
Builder transactionFactory(xxx)

4.通过上述复制构造后,返回真正构建的对象

public Environment build() {
      return environment;
    }

学而时习之 :-)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值