Design pattern ~ Prototype ~

1.First of all

We will summarize the ** Prototype pattern ** in the GoF design pattern.

2. What is the Prototype pattern?

--The English word Prototype means ** prototype ** or ** model **. --The Prototype pattern is a method that ** creates another instance from an instance ** instead of creating an instance from the class with new xxx (). --The operation to make a duplicate is called ** clone **. --In the GoF design pattern, it is classified as ** Design pattern for generation **.

3. Sample class diagram

Prototype.PNG

4. Sample program

A program that underlines or encloses the entered character string.

4-1. Product interface

An interface that defines replication methods. It inherits the Cloneable interface of java.

Product.java


package framework;
import java.lang.Cloneable;

public interface Product extends Cloneable {
    public abstract void use(String s);
    public abstract Product createClone();
}

4-2. Manager class

This class gives instructions and manages product creation.

Manager.java


package framework;
import java.util.HashMap;

public class Manager {

	private HashMap showcase = new HashMap();

	public void register(String name, Product proto) {
        showcase.put(name, proto);
    }

	public Product create(String protoname) {
        Product p = (Product)showcase.get(protoname);
        return p.createClone();
    }
}

4-3. UnderlinePen class

A class that implements the Product interface. This class is a "underline letters" class.

UnderlinePen.java


import framework.Product;

public class UnderlinePen implements Product {

	private char ulchar;

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

	public void use(String s) {

		int length = s.getBytes().length;

		System.out.println(s);

        for (int i = 0; i < length; i++) {
            System.out.print(ulchar);
        }

        System.out.println("");
    }

	public Product createClone() {
        Product p = null;
        try {
            p = (Product)clone();
        } catch (CloneNotSupportedException e) {
        	//Exception thrown when the object's class does not implement the Cloneable interface
            e.printStackTrace();
        }
        return p;
    }
}

4-4. MessageBox class

A class that implements the Product interface. This class is a "enclose character" class.

MessageBox.java


import framework.Product;

public class MessageBox implements Product {

	private char decochar;

	public MessageBox(char decochar) {
        this.decochar = decochar;
    }

	public void use(String s) {

		int length = s.getBytes().length;

		for (int i = 0; i < length + 2; i++) {
            System.out.print(decochar);
        }

		System.out.println("");
        System.out.println(decochar + s + decochar);

        for (int i = 0; i < length + 2; i++) {
            System.out.print(decochar);
        }

        System.out.println("");
    }

	public Product createClone() {
		Product p = null;
		try {
            p = (Product)clone();
        } catch (CloneNotSupportedException e) {
        	//Exception thrown when the object's class does not implement the Cloneable interface
        	e.printStackTrace();
        }
        return p;
    }
}

4-5. Main class

This class performs the main processing.

Main.java


import framework.Manager;
import framework.Product;

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

        Manager manager = new Manager();
        UnderlinePen upen = new UnderlinePen('~');
        MessageBox mbox = new MessageBox('*');
        MessageBox pbox = new MessageBox('+');
        manager.register("strong message", upen);
        manager.register("warning box", mbox);
        manager.register("slash box", pbox);

        Product p1 = manager.create("strong message");
        p1.use("Hello world");
        Product p2 = manager.create("warning box");
        p2.use("Hello world");
        Product p3 = manager.create("slash box");
        p3.use("Hello world");
    }
}

4-6. Execution result

Hello World
===========
*************
*Hello World*
*************
+++++++++++++
+Hello World+
+++++++++++++

5. Benefits

Although it was a relatively simple case in the sample program, creating an instance may require complicated processing or time-consuming processing. It would be very inefficient to do new xxx () every time you create an instance. You can easily create an instance just by creating a Prototype and copying 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 ~ Prototype ~
Prototype pattern
Prototype Pattern
Design pattern ~ Builder ~
Java design pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
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 ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
C ++ design pattern (TemplateMethod pattern)
Design pattern ~ Factory Method ~
GoF design pattern summary
Design pattern ~ Template Method ~
Java design pattern summary
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
Introduction to design patterns Prototype
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)
Memento Pattern
Iterator pattern
Observer Pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Strategy pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Strategy Pattern
Composite Pattern
Singleton Pattern
[Design pattern] Common logic with Template Method
Facade Pattern
Decorator pattern
Flyweight Pattern
Decorator Pattern
Mediator Pattern
Facade pattern
Visitor Pattern
Bridge pattern
PrintObserver "Observer Design Pattern: Description and Implementation Example"
Java8 Lambda expression & Stream design pattern reconsideration --Command pattern -