开始之前我们先说一些和当前无关的东西——一次简单的重构过程。
在《重构》一书中,有一种方法是Replace Constructor with Factory Method,也就是以工厂函数取代构造函数。对于Replace Constructor with Builder来说,想必就是"以生成器取代构造函数"。所以现在,我们需要一个构造函数。
所谓的构造函数,便是在创建对象时调用的特殊方法。
我们构建了一个Book的 Constructor,而这个Book继承自Artistic.
public class Book extends Artistic {
private final String type;
private String author;
public Book(String name, String author, int publishDate) {
super(name, publishDate);
this.author = author;
this.type = "book";
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getType() {
return type;
}
}
而我们所要作的便是构建一本书的信息,于是想试试Builder,而Intellij IDEA
正好有一个这种方法Replace Constructor with Builder。按了一下
alt+command+shift+t
选中Replace Constructor with Builder,于是就有了一个BookBuilder的类
public BookBuilder setName(String name) {
this.name = name;
return this;
}
public BookBuilder setAuthor(String author) {
this.author = author;
return this;
}
public BookBuilder setPublishDate(int publishDate) {
this.publishDate = publishDate;
return this;
}
public Book createBook() {
return new Book(name, author, publishDate);
}
而这不是我们想要的Builder,我们想要的BookDetailsBuilder是这样子的
public BookDetailsBuilder addName(Book book) {
this.name = book.getName();
return this;
}
public BookDetailsBuilder addAuthor(Book book) {
this.author = book.getAuthor();
return this;
}
public BookDetailsBuilder addPublishDate(Book book) {
this.publishDate = book.getPublishDate();
return this;
}
public String build() {
return this.name + "," +
this.author + "," +
this.publishDate + "\n";
}
显然我很懒,传进来的直接是Book的类,只是似乎可以提取这个类。而这只是为了返回结果,对于上面的例子来说,BookBuilder似乎更适合于我们当前的环境,,如果有一天我们需要这样去初始化我们的类的时候。
Book book = new Book (name, date, publishDate, publisher, reviewer, republish..)
So,我们回到设计模式上,看看里面是怎么说的。
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
在我们上面的例子中,我们看到了,是两种不同用途的Builder:
无论是哪一种用法,我们都可以发现,我们都可以用它来执行繁重的、复杂的构造步骤。无论是在创建一本新的书,还是在获取一本书的详细信息。虽然大可不必如些,只是这是一个好的例子,而仍然不是一个合适的例子。
《设计模式》中说到,适用设计模式有两种情况:
参考书目
围观我的Github Idea墙, 也许,你会遇到心仪的项目