Essential Java Design Patterns: Implementation Examples
Classified in Computers
Written on in
English with a size of 2.99 KB
Memento Pattern
The Memento pattern allows you to capture and externalize an object's internal state so that the object can be restored to this state later.
public class MementoDemo {
public static void main(String[] args) {
Caretaker caretaker = new Caretaker();
Originator originator = new Originator();
originator.setState("State1");
caretaker.addMemento(originator.save());
originator.restore(caretaker.getMemento());
}
}Composite Pattern
The Composite pattern is used to compose objects into tree structures to represent part-whole hierarchies.
public class CompositeDemo {
public static void main(String[] args) {
Box root = initialize();
int[] levels = new int[args.length];
for (int i = 0; i < args.length; i++) {
levels[i] = Integer.parseInt(args[i]);
}
root.traverse(levels);
}
private static Box initialize() {
Box[] nodes = new Box[7];
nodes[1] = new Box(1);
int[] waves = {1, 4, 7};
for (int i = 0; i < 3; i++) {
nodes[2] = new Box(21 + i);
nodes[1].add(nodes[2]);
int level = 3;
for (int j = 0; j < 4; j++) {
nodes[level - 1].add(new Product(level * 10 + waves[i]));
nodes[level] = new Box(level * 10 + waves[i] + 1);
nodes[level - 1].add(nodes[level]);
nodes[level - 1].add(new Product(level * 10 + waves[i] + 2));
level++;
}
}
return nodes[1];
}
}Factory Method Pattern
The Factory Method pattern provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
public class FactoryMethodDemo {
public static void main(String[] args) {
DecodedImage decodedImage;
ImageReader reader = null;
String image = args[0];
String format = image.substring(image.indexOf('.') + 1);
if (format.equals("gif")) {
reader = new GifReader(image);
}
if (format.equals("jpeg")) {
reader = new JpegReader(image);
}
assert reader != null;
decodedImage = reader.getDecodeImage();
System.out.println(decodedImage);
}
}Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
public final class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance(String value) {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}