设计模式之-Builder模式
场景引入:
一个类,如果有多个属性时,在创建对象,如何对属性进行赋值呢?
1.通过构造器赋值,这种方案优点时一次性赋值完成,但是多种属性的组合,导致构造器会非常多。
2.通过setter方法赋值,方案优点代码直观简洁,缺点会出现javabean难一致的情况(多线程情况下);
今天,我们学习建造者模式,用一种全新的方式来创建安全的一致的对象。
代码实现:
class BeanFactory{ private String userName; private String passWord; private String url; private int port; public String toString(){ return "{userName="+userName+",passWord="+passWord+",url="+url+",port="+port+"}"; } public BeanFactory(BeanFactoryBuilder builder){ this.userName = builder.userName; this.passWord = builder.passWord; this.url = builder.url; this.port = builder.port; } static class BeanFactoryBuilder{ private String userName; private String passWord; private String url; private int port; public BeanFactoryBuilder setUserName(String userName){ this.userName= userName; return this; } public BeanFactoryBuilder setPassWord(String passWord){ this.passWord= passWord; return this; } public BeanFactoryBuilder setUrl(String url){ this.url= url; return this; } public BeanFactoryBuilder setPort(int port){ this.port= port; return this; } public BeanFactory build(){ return new BeanFactory(this); } } }
测试类:
//测试类 public class Test{ public static void main(String[] args){ BeanFactory factory = new BeanFactory.BeanFactoryBuilder() .setUserName("lucy"). setPassWord("123456"). setUrl("www.baidu.com"). setPort(8080). build(); System.out.println(factory); } }
其实,在Mybatis中的SqlSessionFactoryBuilder就是通过这种方式来生成SqlSessionFactory实例的!