Design pattern ~ Flyweight ~

1.First of all

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

2. What is the Flyweight pattern?

――The English word Flyweight means ** flyweight **. Represents the lightest weight class in boxing. --The weight in the Flyweight pattern is the memory usage. --The Flyweight pattern is a method that ** shares instances as much as possible to reduce memory usage **. --The GoF design patterns are classified as ** structural design patterns **.

3. Sample class diagram

Flyweight.PNG

4. Sample program

A program that reads large text from a file and displays it.

4-1. BigChar class

A class that represents large letters.

BigChar.java


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BigChar {

	//Character name
	private char charname;
	//A character string that represents a large character('#' '.' '\n'Column)
	private String fontdata;

	public BigChar(char charname) {
		this.charname = charname;
		try {
			BufferedReader reader = new BufferedReader(
					new FileReader("big" + charname + ".txt"));
			String line;
			StringBuffer buf = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				buf.append(line);
				buf.append("\n");
			}
			reader.close();
			this.fontdata = buf.toString();
		} catch (IOException e) {
			this.fontdata = charname + "?";
		}
	}

	//Display large characters
	public void print() {
		System.out.print(fontdata);
	}
}

4-2. BigCharFactory class

A class that is created while sharing an instance of BigChar.

BigCharFactory.java


import java.util.HashMap;

public class BigCharFactory {

	//Manage instances of BigChar that you have already created
	private HashMap pool = new HashMap();

	private static BigCharFactory singleton = new BigCharFactory();

	private BigCharFactory() {
	}

	//Get only one instance
	public static BigCharFactory getInstance() {
		return singleton;
	}

	//BigChar instantiation(share)
	public synchronized BigChar getBigChar(char charname) {
		BigChar bc = (BigChar) pool.get("" + charname);
		if (bc == null) {
			bc = new BigChar(charname);
			pool.put("" + charname, bc);
		}
		return bc;
	}
}

4-3. BigString class

It is a class that represents a "large character string" created by collecting BigChar.

BigString.java


public class BigString {

	private BigChar[] bigchars;

	public BigString(String string) {
		bigchars = new BigChar[string.length()];
		BigCharFactory factory = BigCharFactory.getInstance();
		for (int i = 0; i < bigchars.length; i++) {
			bigchars[i] = factory.getBigChar(string.charAt(i));
		}
	}

	public void print() {
		for (int i = 0; i < bigchars.length; i++) {
			bigchars[i].print();
		}
	}
}

4-4. Main class

This class performs the main processing.

Main.java


public class Main {
	public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println("Usage: java Main digits");
			System.out.println("Example: java Main 1212123");
			System.exit(0);
		}
		BigString bs = new BigString(args[0]);
		bs.print();
	}
}

4-5. Data

Please refer to the following txt file. https://github.com/i-tanaka730/design_pattern/tree/master/src/Flyweight

4-6. Execution result

..##########....
..##......##....
..........##....
........##......
......##........
......##........
......##........
................
......##........
..######........
......##........
......##........
......##........
......##........
..##########....
................
..##########....
..##......##....
..........##....
........##......
......##........
......##........
......##........
................
..##########....
..##............
..##............
..########......
..........##....
..##......##....
....######......
................。

5. Benefits

Sharing an instance reduces memory usage because you don't have to renew each time. More generally, sharing an instance can reduce the amount of ** resources ** required to create an instance. A resource is a resource on a computer, and memory is a type of resource. Time is also a resource. If it takes a certain amount of time to new an instance, you can reduce the number of new instances by sharing the instance using the Flyweight pattern. This can speed up the program.

  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 ~ Flyweight ~
Flyweight 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 ~ 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
Introduction to design patterns (Flyweight)
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
Decorator 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 -