Give example of APIs in Java which uses Flyweight and Template Method patterns?
Give example of APIs in Java which uses Flyweight and Template Method patterns?
Flyweight Pattern Example:
java.lang.Integer.valueOf(int)
Integer class has a valueOf(int) method that returns a cached instance of Integer representing the specified int value without creating new object every time. This method is likely to yield significantly better space and time performance by caching frequently requested values. Similarly the valueOf(type) method in the classes Boolean, Byte, Character, Short, Float, Double and Long uses Flyweight pattern.
Template Method Pattern Example:
java.io.InputStream.read(byte b[], int off, int len)
The read(byte[] b, int off, int len) method for class InputStream simply calls the method read() repeatedly. The read() method is defined as abstract method in this class and subclasses of InputStream (like FileInputStream, BufferedInputStream….) must provide an implementation for reading a byte of data for the appropriate stream in this method.
Similarly the write(byte[], int, int) method in java.io.OutputStream uses Template method pattern.