设计模式之Builder模式
前两天,看的Google Collections 的集合组件,看了源代码,发现很多东西都是使用builder来创建,今天也上网查了些东西学习学习,发现多看看开源的源代码还是挺有好处的。今天模仿着Google Collections里面的东东写了一个Demo,呵呵,和标准的Builder模式写法不太相同,不过思想是一样的。贴个Demo程序就好了,模拟一个Bean对象的创建。
//Builder模式的角色:[Product]要生产的最终物品 /** * 用户对象 */ public class User { // 用户名 private String userName; // 用户密码 private String password; // 用户姓名 private String name; // 可看做[Director] 产流水线,负责产品的生产和组织 private User(Builder builder){ this.userName = builder.userName; this.password = builder.password; this.name = builder.name; } //getter方法 public String getUserName() { return userName; } public String getPassword() { return password; } public String getName() { return name; } // Builder模式的角色:[Builder]能进行生产的工作和获得生产的结果 /** * 创建该用户的建立者 * @param userName 用户名 * @return Builder对象 */ public static Builder builder(String userName){ return new Builder(userName); } // 创建者对象 public static final class Builder{ // Builder模式的角色:[Part]产品的基本组成部分 //用户名无法更改 private final String userName ; //密码 private String password; //真实姓名 private String name; //创建对象时必须指定用户名 public Builder(String userName){ this.userName = userName; } /** * 设置密码 * @param password 密码 * @return Builder对象 */ public Builder setPassword(String password){ this.password = password; return this; } /** * 设置姓名 * @param name 真实姓名 * @return Builder对象 */ public Builder setName(String name){ this.name = name; return this; } /** * 创建用户对象 * @return 用户对象 */ public User build(){ //这里在创建对象之前可以进行验证性操作, //而单纯的Bean对象不能进行验证性操作. //普通的做法:User user = new User(); user.setXXX()... //普通的做法使得创建对象和对对象的赋值操作分离开来 //如果用户名为空,则无法创建该对象 if(userName == null || userName.isEmpty()){ throw new IllegalArgumentException("用户名为空,无法创建对象"); } return new User(this); } } }
看Builder创建过程:
public class Test { public static void main(String[] args) { User.Builder builder = User.builder("cst"); builder.setName("chenshuting"); builder.setPassword("123"); User user = builder.build(); System.out.println(user.getUserName()); System.out.println(user.getPassword()); System.out.println(user.getName()); } }
继续学习ing~~~~
2024年1月23日 19:40
JNANABHUMI AP provides all latest educational updates and many more. The main concept or our aim behind this website has been the will to provide resources full information on each topic which can be accessed through Internet. To ensure that every readers get’s what important and worthy about the topic they search and link to hear from us. jnanabhumiap.in Jnanabhumi AP is a startup by passionate webmasters and bloggers who have passion to provide engaging content which is accurate, interesting and worthy to read. We are mope like a web community where you can find different information’s, resources, topics on day to day incidents or news. We provide you the finest of web content on each and every topics possible with help of editorial and content team.