Builder pattern

What is a Builder pattern?

It refers to a pattern in which each part that makes up the whole is made and assembled step by step.

The role of Builder

The Builder role defines the interface for creating an instance. The Builer role provides methods for creating each part of the instance.

package builder2;

public abstract class Builder {
	public abstract void makeTitle(String title);
	public abstract void makeString(String str);
	public abstract void makeItems(String[] items);
	public abstract void close();
}

The role of Concrete Builder

The ConcreteBuilder role is a class that implements the interface of the Builder role. The method called in the actual instantiation is defined here. In addition, a method is prepared to obtain the final result.

package builder2;

public class TextBuilder extends Builder {
	private StringBuffer buffer = new StringBuffer();

	@Override
	public void makeTitle(String title) {
		buffer.append("====================\n");
		buffer.append("「" + title + "」\n");
		buffer.append("\n");
	}

	@Override
	public void makeString(String str) {
		buffer.append('■' + str + "\n");
		buffer.append("\n");
	}

	@Override
	public void makeItems(String[] items) {
		for (int i = 0; i < items.length; i++) {
			buffer.append("・" + items[i] + "\n");
		}
		buffer.append("\n");
	}

	@Override
	public void close() {
		buffer.append("====================\n");
	}

	public String getResult() {
		return buffer.toString();
	}
}
package builder2;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class HtmlBuilder extends Builder {
	private String fileName;
	private PrintWriter writer;

	@Override
	public void makeTitle(String title) {
		fileName = title + ".html";
		try {
			writer = new PrintWriter(new FileWriter(fileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		writer.println("<html><head><title>" + title + "</title></head></body>");
		//Output title
		writer.println("<h1>" + title + "</h1>");
	}

	@Override
	public void makeString(String str) {
		writer.println("<p>" + str + "</p");
	}

	@Override
	public void makeItems(String[] items) {
		writer.println("<ul>");
		for (int i = 0; i < items.length; i++) {
			writer.println("<li>" + items[i] + "</li>");
		}
		writer.println("</ul>");
	}

	@Override
	public void close() {
		writer.println("</body></html>");
		writer.close();
	}

	public String getResult() {
		return fileName;
	}
}

The role of Director

The Director role creates an instance using the Builder role interface. No programming that depends on the ConcreteBuilder role. Use only the methods of the Builder role so that it works regardless of the ConcreteBuilder role.

package builder2;

public class Director {
	private Builder builder;
	public Director(Builder builder) {
		this.builder = builder;
	}

	public void construct() {
		builder.makeTitle("Greeting");
		builder.makeString("From morning to noon");
		builder.makeItems(new String[] {
				"Good morning.",
				"Hello."
		});

		builder.makeString("At night");
		builder.makeItems(new String[] {
				"Good evening.",
				"good night.",
				"goodbye."
		});
		builder.close();
	}
}

The role of Client

A role that uses the Builder pattern.

package builder2;

public class Main {

	public static void main(String[] args) {

		if (args.length != 1) {
			usage();
			System.exit(0);
		}

		if (args[0].equals("plain")) {
			TextBuilder textBuilder = new TextBuilder();
			Director director = new Director(textBuilder);
			director.construct();
			String result = textBuilder.getResult();
			System.out.println(result);

		} else if (args[0].equals("html")) {
			HtmlBuilder htmlBuilder = new HtmlBuilder();
			Director director = new Director(htmlBuilder);
			director.construct();
			String fileName = htmlBuilder.getResult();
			System.out.println(fileName + "Was created");

		} else {
			usage();
			System.exit(0);
		}
	}

	public static void usage() {
		System.out.println("Usage:java Main plain Document creation in plain text");
		System.out.println("Usage:java Main html Document creation with HTML file");
	}
}

Results when using TextBuilder

スクリーンショット 2020-09-04 10.51.50.png

Results when using HtmlBuilder

スクリーンショット 2020-09-04 10.55.07.png

In this program, the Main class does not know (do not call) the method of the Builder class. The Main class calls only the Construct method of the Director class. The Director class then works and the document is complete. When the Director class gets the job done, the Main class doesn't mind. On the other hand, the Director class knows the Builder class. The Director class builds the document using the methods of the Builder class. However, the Director class doesn't know what the class it's actually using is "really". You don't have to know if it's TextBuilder or HtmlBuilder. This is because the Director class uses only the methods of the Builder class, and the subclasses of the Builder class implement the methods. It is possible to replace it because you do not know it. It is highly valuable as a part because it can be replaced.

https://github.com/aki0207/builder2

I used this as a reference. Augmented and Revised Introduction to Design Patterns Learned in Java Language

Recommended Posts

Builder pattern
Builder Pattern
Design pattern ~ Builder ~
Design pattern (2): Builder
Builder pattern (Effective Java)
Prototype pattern
Memento Pattern
Mediator pattern
Composite pattern
Observer Pattern
Bridge Pattern
Command Pattern
Strategy pattern
Iterator Pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Strategy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
Facade Pattern
Decorator pattern
Flyweight Pattern
Decorator Pattern
Mediator Pattern
Facade pattern
Visitor Pattern
Bridge pattern
Object Mother pattern and Test Data Builder pattern
abstract Factory Pattern
[Java] Strategy pattern
Design pattern ~ Visitor ~
Java design pattern
java callback pattern
Test Data Builder pattern ~ Improve maintainability of test code
Design pattern ~ Proxy ~
Design pattern ~ State ~
Factory Method Pattern
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (1): AbstractFactory
[Java] Singleton pattern
Design pattern ~ Command ~
Abstract Factory pattern
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Template Method pattern
Design pattern ~ Decorator ~
Template Method Pattern
Design pattern ~ Interpreter ~
Factory Method pattern
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
[Java] Adapter pattern
Design pattern ~ Memento ~
Design pattern ~ Adapter ~