Design pattern ~ Builder ~

1.First of all

Here is a summary of the ** Builder pattern ** in the GoF design pattern.

2. What is a Builder pattern?

--The English word Build means ** to build a big thing with a structure **. ――When you make something with a complicated structure, it is difficult to complete it all at once. First, make each part that is building the whole, and then build it step by step. --The Builder pattern is a method of assembling instances with a structure **. --In the GoF design pattern, it is classified as ** Design pattern for generation **.

3. Sample class diagram

Builder.PNG

4. Sample program

A program that outputs documents in plain text and HTML format.

4-1. Builder class

An abstract class that defines methods for constructing a document.

Builder.java


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();
}

4-2. Guide class

A class that creates a single document.

Guide.java


public class Guide {

	private Builder builder;

	public Guide(Builder builder) {
		this.builder = builder;
	}

	public void construct() {
		builder.makeTitle("About barbecue");
		builder.makeString("Date and time");
		builder.makeItems(new String[]{
			"2019/2/28 (wood)",
			"11:00~",
		});
		builder.makeString("place");
		builder.makeItems(new String[]{
			"xxx city xxx barbecue area",
		});
		builder.makeString("Belongings");
		builder.makeItems(new String[]{
			"towel",
			"meat",
			"drink",
			"(Abbreviation)",
		});
		builder.close();
	}
}

4-3. TextBuilder class

A class that creates a document in plain text.

TextBuilder.java


public class TextBuilder extends Builder {

	private StringBuffer buffer = new StringBuffer();

	public void makeTitle(String title) {
		buffer.append("==============================\n");
		buffer.append("『" + title + "』\n");
		buffer.append("\n");
	}

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

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

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

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

4-3. HTMLBuilder class

A class that creates a document with an HTML file.

HTMLBuilder.java


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

public class HTMLBuilder extends Builder {

	private String filename;
	private PrintWriter writer;

	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>");
		writer.println("<h1>" + title + "</h1>");
	}

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

	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>");
	}

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

	public String getResult() {
		return filename;
	}
}

4-5. Main class

This class performs the main processing.

Main.java


public class Main {
	public static void main(String[] args) {

		if (args.length != 1) {
			System.exit(0);
		}
		if (args[0].equals("plain")) {
			TextBuilder textbuilder = new TextBuilder();
			Guide guide = new Guide(textbuilder);
			guide.construct();
			String result = textbuilder.getResult();
			System.out.println(result);
		} else if (args[0].equals("html")) {
			HTMLBuilder htmlbuilder = new HTMLBuilder();
			Guide guide = new Guide(htmlbuilder);
			guide.construct();
			String filename = htmlbuilder.getResult();
			System.out.println(filename + "Has been created.");
		} else {
			System.exit(0);
		}
	}
}

4-6. Execution result

4-6-1. Text
==============================
"About barbecue"

■ Date and time

・ 2019/2/28 (wood)
・ 11:00~

■ Location

・ Xxx city xxx barbecue area

■ What to bring

·towel
·meat
·drink
・(Abbreviation)

==============================

4-6-2. HTML bbq.PNG

5. Benefits

Looking at the sample program, the Main class doesn't know how to build a document (a method of the Builder class). The Main class can construct sentences simply by calling the construct method of the Guide class. Also, the Guide class uses the Builder class to build the document, but the Guide class doesn't know what class it's actually using (TextBuilder or HTMLBuilder). Whether you give an instance of TextBuilder to Guide or an instance of HTMLBuilder to Guide, it works correctly because the Guide class doesn't know the specific class of the Builder class. ** You can replace it because you don't know it, and the value as a part increases because you can replace it. ** **

  1. GitHub

7. List of design patterns

-** GoF design pattern summary **

8. Reference

This article and sample program were created based on the following books.

-** Introduction to design patterns learned in Java language **

It was very easy to understand and I learned a lot. Thank you. The detailed explanations of the design patterns and sample programs are written, so please take a look at the books as well.

Recommended Posts

Design pattern ~ Builder ~
Design pattern (2): Builder
Builder pattern
Builder Pattern
Design pattern ~ Visitor ~
Java design pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (1): AbstractFactory
Design pattern ~ Command ~
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Design pattern ~ Decorator ~
Design pattern ~ Interpreter ~
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
C ++ design pattern (TemplateMethod pattern)
Design pattern ~ Factory Method ~
Design pattern ~ Abstract Factory ~
GoF design pattern summary
Design pattern ~ Template Method ~
Builder pattern (Effective Java)
Java design pattern summary
Introduction to Design Patterns (Builder)
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
Rethinking design patterns with Java8 lambda expressions & Stream --Builder pattern -
Ruby design pattern template method pattern memo
C # chewed design pattern: Template Method
Application example of design pattern (No. 1)
Java beginner design pattern (Factory Method pattern)
Prototype pattern
Mediator pattern
Iterator pattern
Composite pattern
Object Mother pattern and Test Data Builder 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
[Design pattern] Common logic with Template Method
Facade Pattern
Decorator pattern
Flyweight Pattern