100000380
Points
Questions
185
Answers
186
-
Template Method pattern is a behavioral pattern which is used to manage algorithms. Template Method pattern is used when two or more implementations of a similar algorithm exist. As per GoF, intent of Template Method pattern is “Defines the skeleton of an algorithm in a method, deferring some steps to subclasses”.
In Template Method pattern, an abstract clasas exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementations as per need basis but the invocation is to be in the same way as defined by the abstract super class.
Let us understand this with an example: In this example, Parser is the abstract super class that defines the algorithm which is implemented by the subclasses XMLParser and JSONParser.
public abstract class Parser {// Template Method – final so that subclasses don’t override public final void parse() {
readData();
processData();
displayOutput();
}
public abstract void readData();
public void processData() {
// Process data from the parser….
System.out.println(“Processing data….”);
}
public abstract void displayOutput();
}
public class XMLParser extends Parser{@Override public void readData() {
System.out.println(“Reading data from XML file….”);
}
@Override
public void displayOutput() {
System.out.println(“Displays output from parsed XML file….”);
}
}
public class JSONParser extends Parser {@Override public void readData() {
System.out.println(“Reading JSON objects….”);
}
@Override
public void displayOutput() {
System.out.println(“Displays output from JSON objects….”);
}
}
public class TestTemplate {
public static void main(String[] args) {
Parser parser = new XMLParser();
parser.parse();
parser = new JSONParser();
parser.parse();
}
}
Output:
Reading data from XML file….
Processing data….
Displays output from parsed XML file….
Reading JSON objects….
Processing data….
Displays output from JSON objects….
Interesting point to note in template method pattern is that superclass template method calls methods from subclasses.
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1305 views
- 1 answers
- 0 votes
-
Singleton Pattern Example:
java.lang.Runtime.getRuntime()
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The Runtime.getRuntime() method in java.lang package returns the same instance every time it is called.
Factory Method Pattern Example:
java.util.Calendar.getInstance()
java.util.Calendar is an abstract class. The getInstance() method of Calendar class is a static method that returns an implementation of the Calendar class depending on the input. The default method without parameter returns an implementation of Calendar class based on the current time in the default time zone with the default locale.
java.util.Calendar.getInstance(Locale aLocale)
This is an overloaded method which returns a calendar using the default time zone and specified locale. The Calendar returned is based on the current time in the default time zone with the given locale.
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1999 views
- 1 answers
- 0 votes
-
Flyweight pattern should be used when:
- There is a need to create large number of similar objects
- Many similar objects are used and the storage cost is high
- Most of the object attributes can be made external and shared
- The identity of each object does not matter
- A few shared objects would easily replace many unshared objects
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1283 views
- 1 answers
- 0 votes
-
Flyweight is a structural pattern that is used when there is a need to create large number of similar objects. It reduces the number of objects created thereby decreasing memory footprint and increasing performance. Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. Factory pattern and Singleton pattern are used in implementing Flyweight pattern. Let us understand this with an example.
This example reuses the Factory pattern example discussed earlier.
ShapeType is an enum, Shape is an abstract class which has Square and Rectangle as concrete classes. The Flyweight pattern is demonstrated with the FlyweightShapeFactory class as below. The FlyweightShapeFactory class is our Flyweight factory. It utilizes the singleton pattern so that we only have once instance of the factory. The FlyweightShapeFactory creates an EnumMap pool of shapes which stores all the instances of the different types of shapes. Only one instance of each type is created, and this occurs on-demand.
public class FlyweightShapeFactory { private static FlyweightShapeFactory factory = null; private Map<ShapeType, Shape> instancePool = null; private Shape shape = null; private FlyweightShapeFactory() { instancePool = new EnumMap<ShapeType, Shape>(ShapeType.class); } public static FlyweightShapeFactory getInstance() { if (factory == null) { factory = new FlyweightShapeFactory(); } return factory; } public Shape createShape(ShapeType shapeType) { if (instancePool.containsKey(shapeType)) { return instancePool.get(shapeType); } switch (shapeType) { case SQUARE: shape = new Square(); break; case RECTANGLE: shape = new Rectangle(); break; } instancePool.put(shapeType, shape); return shape; } }
/* This can be tested with the below code. When we test this, we see that it creates the Shape object first time and reuse from next time instead of creating new objects */
public class TestFlyweight { public static void main(String arg[]) { FlyweightShapeFactory factory = FlyweightShapeFactory.getInstance(); for (int index = 0; index < 5; index++) { Shape shape = factory.createShape(ShapeType.SQUARE); shape.displayShapeInfo(); shape = factory.createShape(ShapeType.RECTANGLE); shape.displayShapeInfo(); } } }
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1191 views
- 1 answers
- 0 votes
-
Benefits of Factory pattern are:
- Factory pattern creates objects without exposing the instantiation logic and refers to the newly created object through a common interface.
- Factory pattern removes the instantiation of actual implementation classes from client code, making it more robust, less coupled and easy to extend.
- Factory pattern provides abstraction between implementation and client classes through inheritance.
Factory pattern is most suitable where there is some complex object creation steps are involved.
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1349 views
- 1 answers
- 0 votes
-
Factory pattern is a creational pattern which uses factory methods to deal with the problem of creating objects without specifying the class of the object that will be created. The created object is returned by the factory method in form of an interface/abstract class and all classes that can be created must implement this interface or extend the abstract class. Factory pattern creates objects without exposing the instantiation logic. The client invoking the factory method provides an input which is used to decide which actual class to instantiate. This pattern is widely used in frameworks like Struts, JSF and Spring.
Let us understand this concept through an example. In the example below the client is the Factory class, the factory method is createShape, input used to decide the actual shape is shapeEnum, Square and Rectangle are the two concrete implementations of the abstract class Shape which is returned to the client.
// ShapeType is an enum to hold the// types of shapespublic enum ShapeType { SQUARE, RECTANGLE;
}
// Shape is an abstract super class for all      // shapespublic abstract class Shape {private ShapeType shape; public Shape(ShapeType shape) {
this.shape = shape;
}
public abstract void display();
}
// Square, Rectangle are concrete                   // implementations of Shape for a type.public class Square extends Shape{public Square() { super(ShapeType.SQUARE);
}
@Override
public void display() {
System.out.println(“Square shape….”);
}
}
// ShapeFactory.java is our main class implemented using factory pattern.// It instantiates a shape based on its type.public class ShapeFactory { public static Shape createShape(ShapeType shapeEnum) {
Shape shape = null;
switch(shapeEnum){
case SQUARE:
shape = new Square();
break;
case RECTANGLE:
shape = new Rectangle();
break;
}
return shape;
}
}
// When you test this, will get the appropriate output….
public class Factory {
public static void main(String arg[]) {
Shape shape = ShapeFactory.createShape(ShapeType.SQUARE);
shape.display();
shape = ShapeFactory.createShape(ShapeType.RECTANGLE);
shape.display();
}
}
Output:
Square shape….
Rectangle shape….
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1292 views
- 1 answers
- 0 votes
-
Singleton allows only one instance of class per JVM. If a singleton object is deployed in a clustered environment, each JVM will have their own copy of the singleton object. To ensure that only ONE singleton object is available for the entire application across JVMs, some additional design approach or different techniques like JMS, Custom API, 3rd party tools etc. can be adopted.
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1373 views
- 1 answers
- 0 votes
-
Thread-safe singleton class can be created using inner static class approach.
public class Singleton { private Singleton() { } private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance(){ return SingletonHolder.INSTANCE; } }
Here the private static inner class contains the instance of the Singleton class. When the Singleton class is loaded, SingletonHolder class is not loaded into memory. SingletonHolder class gets loaded on first invocation of the getInstance method and creates the Singleton class instance. Java Language Specification guarantees the class initialization process to be serial (non-concurrent) so no synchronization is required in the getInstance method. This solution guarantees single instance and achieves better performance than using synchronized keyword.
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 5589 views
- 1 answers
- 0 votes
-
The easiest way to create a thread-safe singleton class is to make the getInstance method synchronized thereby allowing only one thread to execute this method at a time.
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Above code works fine and provides thread-safety but it reduces performance because of cost associated with the synchronized method. It can be noticed that this design is not optimal as every invocation of getInstance method is synchronized while the requirement is only for the first call. A slightly better solution is to synchronize only the new instance creation instead of the entire method. This solution requires an additional check for null inside the synchronized block and is termed as double check locking optimization.
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1520 views
- 1 answers
- 0 votes
-
Singleton pattern is a creational pattern that ensures that only one instance of a class is created per JVM. It provides global point of access to the object. Some practical uses of Singleton pattern are logging, caches, thread pools etc.
Singleton pattern in Java can be created as follows:
- Declare private constructor to restrict instantiation of the class from other classes.
- Declare private static variable in the class to store the only instance of the class.
- Declare public static method that returns the instance of the class. This is the global access point for outer world to get the instance of the singleton class.
public class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
The above basic design for Singleton is not fool proof due to two reasons:
- It is not thread safe and it is possible to create multiple instances in multiple threads invoke the getInstance method at the same time.
- The private constructor approach can be broken through reflection
This answer accepted by JavaNinja. on 18th September 2018 Earned 15 points.
- 1413 views
- 1 answers
- 0 votes