Quantcast
Channel: Reza's Weblog
Viewing all articles
Browse latest Browse all 50

Template Method Pattern in Spring

$
0
0

Many people do not like Template Method pattern but I usually use it and it has been useful in some situations. Although in Spring Framework there is a small trick to apply. Imaging this:

public abstract class Calculator{

abstract method1

abstract method2

concrete method3


public class XCalculator extends Calculator{}

public class YCalculator extends Calculator{}

Now there is a service class that conditionally needs to use either XCalcuator or YCalculator. In Srping there is a problem with Service class. Either you have to inject both xCalc and yCalc which is odd:

Public class Service{

Calculator xCalc;

Calculator yCalc;

if(x) then use xCalc

else use yCalc

}

Or use the following that many in Spring community do not like as the X/YCalculator are being instantited not injected.

 Public class Service{

if(x) then use calc = new XCalculator();

else use calc = new YCalculator();

}

I am fine with this and hate injecting both calculators together and use only one! But still there is a point here to notice: As we instantiate X/YCalculators, if they have dependencies to other spring beans then we will get NPE at runtime. What we have to do is to inject whatever bean they need to their constructor. Suppose XCalcuator needs bean XyzDao from Srping:

Public class Service{

XyzDao xyz; //injected by Spring

if(x) then use calc = new XCalculator(xyz);

else use calc = new YCalculator();

}

This way we avoid NPE.


Viewing all articles
Browse latest Browse all 50

Trending Articles