I think you are looking for flyweight pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory.
For flyweight pattern objects should be immutable so that it can be shared with thinking about thread safety. With immutable objects thread safety comes free. You can do something as below. Either you can take PriceCategory
as an enum
or some immutable object. As enum
is inherently immutable so we can have minimal object creation footprint and also safe.
public class Handler {
public enum PriceCategory{
LOW,MID, HIGH;
}
private static class Element{
private int min;
private int max;
private Element(int min, int max){
this.min=min;
this.max=max;
}
}
private static final Map<Element, PriceCategory> map = new HashMap<Element, PriceCategory>();
static{
map.put(new Element(100, 200), Handler.PriceCategory.LOW);
map.put(new Element(201, 300), Handler.PriceCategory.MID);
map.put(new Element(301, 400), Handler.PriceCategory.HIGH);
}
public static String getClassificationForProduct(ProductData product) {
//here just check for which range this product price is belonging and return that enum/immutable object
}
}