Facade pattern in Java

Introduction

Introducing the design patterns of [GoF](https://ja.wikipedia.org/wiki/Gang of for _ (Information Engineering)) ["Introduction to Design Patterns Learned in the Augmented and Revised Java Language"]( https://www.amazon.co.jp/ Augmented and revised edition Introduction to design patterns learned in Java language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _ Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP) I will summarize about.

Facade pattern

What is Facade

Translated into Japanese, it means "front (of the building)". If you use a program that involves multiple classes, you need to execute the methods in each class in the proper order. For example, "If you want to perform process X, call the B method of the A class, then the D and E methods of the C class, and finally the G method of the F class." There weren't too many classes and methods in the example above, but the higher the number, the more complex the control of classes and methods when doing ** processing. ** ** In such a case, the ** Facade pattern ** is a pattern that provides an interface (API) that serves as a "window" when viewed from the processing requester. By applying this pattern, the requester does not need to know the control of complicated processing.

Character

The Facade pattern is used by the classes that appear in the class diagram below. image.png

Implementation class

-** Other classes ** These are the classes that are called to do the processing. There are no particular restrictions on what should be implemented. There is nothing particularly difficult, but the point is that the classes used are not aware of the Facade, which is the contact point. This is because other classes do not call Facade.

Concrete example

As a concrete example, it will be explained based on the following class. image.png

Implementation class

-** ListFacade class **

ListFacade.java


import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class ListFacade {
	private ListFacade() { //Private declaration to prevent instantiation with new
	}

	public static void makeMemberList(String inputFileName, String outputFileName) {
		try {
			Properties memberProperties = MemberList.getProperties(inputFileName);
			outputFileName = "C:\\work\\Facade\\src\\" + outputFileName + ".txt";
			TxtWriter writer = new TxtWriter(new FileWriter(outputFileName));
			Map<String, String> propertiesMap = writer.toMap(memberProperties);
			writer.writeHeader();
			writer.writeContents(propertiesMap);
			writer.writeFooter();
			writer.close();
			System.out.println(String.format("The file was output. file name:%s", outputFileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

The ListFacade class is the contact point for the Main class, which is the Client. You can see that only the statis makeMemberList method is defined, it receives a property from the MemberList class, receives a Map based on that property, and outputs it to a file. If the process is successful, a message indicating that the file has been output is output to the console. The only point is that ** these series of processing flows are described in the ListFacade class, which is the contact point, not in the Main class **. There is nothing particularly difficult about learning patterns.

-** MemberList class **

MemberList.java


import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class MemberList {
	private MemberList() { //Private declaration to prevent instantiation with new
	}

	public static Properties getProperties(String fileName) { //Get Properties from filename
		fileName = "C:\\work\\Facade\\src\\" + fileName + ".txt";
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(fileName));
		} catch (IOException e) {
			System.out.println(String.format("Failed to read the file. file name:%s", fileName));
		}
		return properties;
	}
}

This is the first of two other classes. Only the static getProperties method is defined and returns the properties file by receiving the filename. There is nothing particularly difficult.

-** TxtWriter class **

TxtWriter.java


import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

public class TxtWriter {
	private Writer writer;

	public TxtWriter(Writer writer) { //constructor
		this.writer = writer;
	}

	//Receive property value(Key)Stores more than 25 in Map
	public Map<String, String> toMap(Properties properties) {
		Map<String, String> propertiesMap = new HashMap<>();
		for (Entry<Object, Object> e : properties.entrySet()) {
			if (Integer.parseInt((String) e.getValue()) > 25) {
				propertiesMap.put(e.getKey().toString(), e.getValue().toString());
			}
		}
		return propertiesMap;
	}

	//Output header
	public void writeHeader() throws IOException {
		writer.write("***************Header***************");
		writer.write(System.lineSeparator());
	}

	//Output contents
	public void writeContents(Map<String, String> propertiesMap) throws IOException {
		writer.write("The following members are over 25 years old.");
		writer.write(System.lineSeparator());
		for (Entry<String, String> e : propertiesMap.entrySet()) {
			writer.write("·name:" + e.getKey() + "age:" + e.getValue());
			writer.write(System.lineSeparator());
		}
	}

	//Output footer
	public void writeFooter() throws IOException {
		writer.write("***************Footer***************");
	}

	//close
	public void close() throws IOException {
		writer.close();
	}

}

This is the second of the other classes. Some methods are defined, such as a method that receives a property and stores it in a Map, and a method that outputs it to a text file, but there is nothing particularly difficult about this.

Other

memberList.txt


#name=age
Tanaka_Tarou=25
Hoge_Hogeko=10
Yamada_Hanako=30
Neko_Nekota=50
Foo_Footarou=80

This is the text file to be read by the MemberList class. The key is the name and the value is the age.

Execution class

-** Main class **

Main.java


import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;

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

		// 1.When applying the Facade pattern
		ListFacade.makeMemberList("memberList", "outputFile1");

		// 2.When the Facade pattern is not applied
		try {
			String inputFileName = "memberList";
			String outputFileName = "outputFile2";

			Properties memberProperties = MemberList.getProperties(inputFileName);
			outputFileName = "C:\\work\\Facade\\src\\" + outputFileName + ".txt";
			TxtWriter writer = new TxtWriter(new FileWriter(outputFileName));
			Map<String, String> propertiesMap = writer.toMap(memberProperties);
			writer.writeHeader();
			writer.writeContents(propertiesMap);
			writer.writeFooter();
			writer.close();
			System.out.println(String.format("The file was output. file name:%s", outputFileName));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

** 1. When the Facade pattern is applied **, you can execute the desired process simply by calling the static makeMemberList method for theListFacade class that is the contact point. Also, if you want to perform the process multiple times, just call the method in the same way. , ** 2. If the Facade pattern has not been applied ** In the case of **, the target processing cannot be executed unless the contents described in the ListFacade class are described as they are. Also, if you want to perform processing multiple times, you need to describe as many complicated processes as you want to perform.

(*** This time, other classes are used from the Main class, but it is possible that you can use other classes only from the window by specifying protected by dividing the package **. Here, in order to make it easy to understand the difference between using Facade and not using it, it can also be called from the Client. )

Execution result

The result of executing Main.java is as follows. You can see that there is no difference in the processing results between when the pattern is applied and when it is not applied.

Execution result(console)


The file was output. file name:C:\work\Facade\src\outputFile1.txt
The file was output. file name:C:\work\Facade\src\outputFile2.txt

Execution result(outputFile1.txt)


***************Header***************
The following members are over 25 years old.
・ Name: Yamada_Hanako Age: 30
・ Name: Foo_Footarou Age: 80
・ Name: Neko_Nekota Age: 50
***************Footer***************

Execution result(outputFile2.txt)


***************Header***************
The following members are over 25 years old.
・ Name: Yamada_Hanako Age: 30
・ Name: Foo_Footarou Age: 80
・ Name: Neko_Nekota Age: 50
***************Footer***************

merit

The advantages of the Facade pattern are as follows. ** 1. ** The code can be simplified because the caller does not have to write detailed controls. ** 2. ** You can prevent unintended calls from becoming bugs. ** 3. ** By narrowing down the call port of the interface, it can be loosely coupled with the outside, and reusability is improved.

Summary

You learned about the Facade pattern, which provides a window for controlling complex processes. The sample code is uploaded below, so please refer to it if you like.

-Facade sample code

In addition, other design patterns are summarized below, so please refer to them as well.

-[Updated from time to time] Summary of design patterns in Java

References

-[Introduction to Design Patterns Learned in the Augmented and Revised Java Language](https://www.amazon.co.jp/ Introduction to Design Patterns Learned in the Augmented and Revised Java Language-Hiroshi Yuki / dp / 4797327030 / ref = pd_lpo_sbs_14_t_0? _Encoding = UTF8 & psc = 1 & refRID = 2ZE4GPYNN55JGDR5QMHP)

Recommended Posts

Facade pattern in Java
Singleton pattern in Java
Flyweight pattern in Java
Observer pattern in Java
Iterator pattern in Java
Decorator pattern in Java
Prototype pattern in Java
Proxy pattern in Java
Template Method pattern in Java
Chain of Responsibility pattern in Java
Design Pattern #Facade
Singleton pattern in Python
Linux permissions in Java
Use DataFrame in Java
Visitor pattern in Python
Implement Table Driven Test in Java
Detect and process signals in Java.
Implement the Singleton pattern in Python
Implemented bubble sort in Java (BubbleSort)
GoF java design pattern rough summary
Design patterns to enjoy with frequently used Java libraries --Facade pattern
Overlapping regular expressions in Python and Java
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Express Python yield in JavaScript or Java
Apply Google Java Style formatter in IntelliJ
Learn the design pattern "Command" in Python
Differences in syntax between Python and Java
Get mail using Gmail API in Java
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
[Gang of Four] Design pattern learning --Facade
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "State" in Python
Let's run a Bash script in Java
Learn the design pattern "Adapter" in Python
Learn the design pattern "Facade" with Python