Вопрос

There are price ranges (Low, Mid, High). The price ranges are different for different product type.

I have a handler class which contains all price ranges and it can determine the price range of the product.

E.g:

Product A, Price:200, Price range:50-300 (Mid)

Product B, Price:80, Price range:70-120 (High)

public class Handler {

        // static priceRangeMap for Price ranges

    public static void addPriceRange(PriceRange PriceRange){
        //add price ranges to the priceRangeMap
        //initialised when the application is started
    }

    public static String getClassificationForProduct(ProductData product) {
        //determine classification for a product
    }
}   

public class ProductData {

    public String getClassification() {
        return Handler.getClassificationForProduct(this);
    }
}

I don't wan't to store price ranges in the product because there are a lot of product which has the same ranges.

Is it ugly solution?

Handler.getClassificationForProduct(this);

Is there any better solution?

Это было полезно?

Решение

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
}
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top