Prototype 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.

Prototype pattern

What is Prototype?

Translated into Japanese, it means "prototype". The pattern ** that creates a new instance by copying (duplicate) another class using this ** prototype instance is called the ** Prototype pattern **. Normally, new is used when creating an instance, but in the Prototype pattern, instead of new, use the clone method defined in the java.lang.Object class, which is a superclass of all classes. Create an instance.

Character

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

Abstract class

Implementation class

Concrete example

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

interface

-** Product interface **

Product.java


package framework;

import java.lang.Cloneable;

// 1. java.lang.Inherit Cloneable
public interface Product extends Cloneable {
	public abstract void display(String s);

//2.Declare createClone method
	public abstract Product createClone();
}

The points are the following two points. ** 1. ** It inherits the java.lang.Cloneable interface so that it can be copied with the clone method. ** 2. ** Declaring the createClone method.

I will give a supplementary explanation. The clone method is defined in the java.lang.Object class, which is a superclass of all classes. To execute this clone method, the source class must implement the java.lang.Cloneable interface. If you do not implement the java.lang.Cloneable interface, you will get a CloneNotSupportedException exception. Also, regarding the createClone method, it is a method for using the clone method, but implementation is done by the subclasses Surround class and ʻUnderLine` class.

Implementation class

-** Client class **

Client.java


package framework;

import java.util.*;

public class Client {
	private HashMap<String, Product> stringName = new HashMap<>();

	// 1.Register with HashMap
	public void register(String name, Product pro) {
		stringName.put(name, pro);
	}

	// 2.Use createClone method
	public Product create(String proname) {
		Product p = (Product) stringName.get(proname);
		return p.createClone();
	}
}

The Client class is a class for using the copy method. The points are the following two points. ** 1. ** The instance that implements the Product interface is registered in HashMap by the register method. ** 2. ** You are using the createClone () method inside the create method.

-** Surround class **

Surround.java


import framework.*;

public class Surround implements Product {
	private char srchar;

	public Surround(char srchar) {
		this.srchar = srchar;
	}

	// 1.Implementation of display method
	@Override
	public void display(String s) {
		int length = s.getBytes().length;
		for (int i = 0; i < length + 4; i++) {
			System.out.print(srchar);
		}
		System.out.println("");
		System.out.println(srchar + " " + s + " " + srchar);
		for (int i = 0; i < length + 4; i++) {
			System.out.print(srchar);
		}
		System.out.println("\n");
	}

	// 2.Implementation of createClone method
	@Override
	public Product createClone() {
		Product p = null;
		try {
			p = (Product) clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return p;
	}
}

The Surround class is a class for implementing copy methods. The points are the following two points. ** 1. ** Implements the display method that encloses and displays the character string received when calling the display method with the characters received by the constructor. ** 2. ** Implementing the createClone method.

I will give a supplementary explanation about 2. The points are ** 2 **. The first is the ** point enclosed in the ** try-catch statement. The clone method must implement the java.lang.Cloneable interface as described in the Product interface. If it is not implemented, an exception of CloneNotSupportedException will occur, so it is enclosed in a try-catch statement in consideration of the case where an exception occurs. The second is that the clone method is called within the ** createClone method **. You can only call the clone method from your own class (or subclass). Therefore, in order to call the clone method from the Client class, it is necessary to make the call via another method such as the createClone method.

-** Underline class **

Underline.java


import framework.*;

public class Underline implements Product {
	private char ulchar;

	public Underline(char ulchar) {
		this.ulchar = ulchar;
	}

	// 1.Implementation of display method
	@Override
	public void display(String s) {
		int length = s.getBytes().length;
		System.out.println("\"" + s + "\"");
		System.out.print(" ");
		for (int i = 0; i < length; i++) {
			System.out.print(ulchar);
		}
		System.out.println("\n");
	}

	// 2.Implementation of createClone method
	@Override
	public Product createClone() {
		Product p = null;
		try {
			p = (Product) clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return p;
	}
}

The ʻUnderlineclass is a class for implementing copy methods like theSurroundclass. The points are the following two points. ** 1. ** The character received in the constructor implements thedisplay method, which is displayed as an underline under the character string received when the displaymethod is called. ** 2. ** Implementing thecreateClone` method.

The supplementary explanation is the same as the Surround class, so I will omit it.

Execution class

-** Main class **

Main.java


import framework.*;

public class Main {
	public static void main(String[] args) {
		//Preparation
		Client manager = new Client();
		Underline ul1 = new Underline('-');
		Underline ul2 = new Underline('~');
		Surround sr1 = new Surround('#');
		Surround sr2 = new Surround('@');
		manager.register("underLine text1", ul1);
		manager.register("underLine text2", ul2);
		manager.register("surround text1", sr1);
		manager.register("surround text2", sr2);

		//Generate
		Product p1 = manager.create("underLine text1");
		p1.display("Hello, world.");
		Product p2 = manager.create("underLine text2");
		p2.display("Hello, world.");
		Product p3 = manager.create("surround text1");
		p3.display("Hello, world.");
		Product p4 = manager.create("surround text2");
		p4.display("Hello, world.");
	}
}

In preparation, the register method is used to register the Underline and Surround instances. In the creation, we call the create method to make a copy of the instance and call the display method.

Execution result

The result of executing Main.java is as follows. You can see that each given character is underlined or enclosed.

Execution result


"Hello, world."
 -------------

"Hello, world."
 ~~~~~~~~~~~~~ 

#################
# Hello, world. #
#################

@@@@@@@@@@@@@@@@@
@ Hello, world. @
@@@@@@@@@@@@@@@@@

** * Addition: 2018/11/8 ** I asked links_2_3_4 how to add a double-byte space at the end. Thank you very much.

merit

There are the following three points. ** 1. ** When there are multiple instances of similar classes, it is not necessary to separate the classes and it is easy to manage. ** 2. ** When it is difficult to create an instance from a class, you can easily create an instance. ** 3. ** You can separate the framework from the instance you want to create.

Summary

You learned about the Prototype pattern of copying other classes and creating new instances using the prototype instance. The sample code is uploaded below, so please refer to it if you like.

-Prototype 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

Prototype pattern in Java
Facade pattern in Java
Singleton pattern in Java
Flyweight pattern in Java
Observer pattern in Java
Iterator pattern in Java
Decorator pattern in Java
Proxy pattern in Java
Template Method pattern in Java
Chain of Responsibility pattern in Java
Singleton pattern in Python
Visitor pattern in Python
I wrote a design pattern in kotlin Prototype
Summary of Prototype patterns introductory design patterns learned in Java language
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
Overlapping regular expressions in Python and Java
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
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
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