[JAVA] Design pattern ~ Decorator ~

1.First of all

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

2. What is the Decorator pattern?

--The English word Decorator means ** decorate **. --The Decorator pattern is a ** method of decorating objects more and more **. ――The image is that the objects are decorated one by one so that you can decorate the sponge cake with cream, chocolate, strawberries, etc. --In the GoF design pattern, it is classified as ** Design pattern for generation **.

3. Sample class diagram

Decorator.PNG

4. Sample program

This is a program that decorates the entered character string with a frame.

4-1. Display class

An abstract class for displaying character strings.

Display.java


public abstract class Display {

	//Get the number of horizontal characters
	public abstract int getColumns();
	//Get the number of vertical rows
	public abstract int getRows();
	//Get the string on the specified line
	public abstract String getRowText(int row);

	public void show() {
		for (int i = 0; i < getRows(); i++) {
			System.out.println(getRowText(i));
		}
	}
}

4-2. StringDisplay class

This class is for displaying a character string consisting of only one line.

StringDisplay.java


public class StringDisplay extends Display {

	private String string;

	public StringDisplay(String string) {
		this.string = string;
	}

	public int getColumns() {

		return string.getBytes().length;
	}

	public int getRows() {
		return 1;
	}

	public String getRowText(int row) {
		return (row == 0) ? string : null;
	}
}

4-3. Border class

An abstract class that represents a decorative frame.

Border.java


public abstract class Border extends Display {

	protected Display display;

	protected Border(Display display) {
		this.display = display;
	}
}

4-4. SideBorder class

This class has decorative frames on the left and right.

SideBorder.java


public class SideBorder extends Border {

	public SideBorder(Display display) {
		super(display);
	}

	public int getColumns() {
		//The number of characters is the number of decorative characters added to both sides of the contents
		return 1 + display.getColumns() + 1;
	}

	public int getRows() {
		//The number of lines is the same as the number of lines in the contents
		return display.getRows();
	}

	public String getRowText(int row) {
		return "*" + display.getRowText(row) + "*";
	}
}

4-5. FullBorder class

This class has decorative frames on the top, bottom, left, and right.

FullBorder.java


public class FullBorder extends Border {

	public FullBorder(Display display) {
		super(display);
	}

	public int getColumns() {
		//The number of characters is the number including the left and right decorative characters on both sides of the contents
		return 1 + display.getColumns() + 1;
	}

	public int getRows() {
		//The number of lines is the number of lines in the contents plus the upper and lower decorative characters.
		return 1 + display.getRows() + 1;
	}

	public String getRowText(int row) {
		if (row == 0) {
			//Top frame
			return "+" + makeLine('-', display.getColumns()) + "+";
		} else if (row == display.getRows() + 1) {
			//Bottom frame
			return "+" + makeLine('-', display.getColumns()) + "+";
		} else {
			//other than that
			return "|" + display.getRowText(row - 1) + "|";
		}
	}

	private String makeLine(char ch, int count) {
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < count; i++) {
			buf.append(ch);
		}
		return buf.toString();
	}
}

4-6. Main class

This class performs the main processing.

Main.java


public class Main {

	public static void main(String[] args) {
		Display b1 = new StringDisplay("Hello world");
		b1.show();
		System.out.println("");

		Display b2 = new SideBorder(b1);
		b2.show();
		System.out.println("");

		Display b3 = new FullBorder(b2);
		b3.show();
		System.out.println("");

		Display b4 =
			new FullBorder(
				new SideBorder(
					new FullBorder(
						new StringDisplay("Hello japan"))));
		b4.show();
	}
}

4-7. Execution result

Hello world

*Hello world*

+-------------+
|*Hello world*|
+-------------+

+---------------+
|*+-----------+*|
|*|Hello japan|*|
|*+-----------+*|
+---------------+

5. Benefits

In the Decorator pattern, both the Border and the String Display have a common interface. The interface is the same, but the more you wrap it, the more features you add. At that time, there is no need to modify the person who is wrapped. You can add features without changing what is wrapped.

  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 ~ Decorator ~
Decorator pattern
Decorator Pattern
Design pattern ~ Builder ~
Design pattern ~ Visitor ~
Design pattern ~ Proxy ~
Design pattern ~ Strategy ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
Design pattern ~ Command ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Design pattern ~ Interpreter ~
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
Design pattern ~ Factory Method ~
Design pattern ~ Abstract Factory ~
GoF design pattern summary
Design pattern ~ Template Method ~
Java design pattern summary
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
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
Memento Pattern
Mediator pattern
Iterator pattern
Composite pattern
Observer Pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder 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
Flyweight 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 -