0

有价格范围(低,中,高)。不同产品类型的价格范围不同。需要Java设计模式建议。 (具有静态参数和方法的处理器)

我有一个处理程序类,其中包含所有价格范围,它可以确定产品的价格范围。

例如:

产品A,价钱:200,价格范围:50-300(MID)

产品B,价格:80,价格范围:70-120(高)

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); 
    } 
} 

我不想在产品中存储价格范围,因为有很多产品具有相同的范围。

这是否是丑陋的解决方案?

Handler.getClassificationForProduct(this);

有没有更好的解决办法?

+0

成分浮现在脑海。这不是一种真正的设计模式,但是如果您想要可重复使用的价格范围,请将其设为一个班级。 –

+0

有没有什么方法/模式可以识别产品A是否与产品C相似,或者没有任何与其相关的属性变量? – charlypu

+0

关于你的编辑,是的,你的Handler类有一个不好的代码异味,从它的静态方法开始。我认为你应该摆脱它。 –

回答

1

我认为您在寻找flyweight pattern。轻量级是通过与其他类似对象共享尽可能多的数据来最大限度地减少内存使用的对象;当简单的重复表示使用不可接受的内存量时,这是一种大量使用对象的方法。

对于flyweight模式对象应该是不可变的,以便它可以与思考线程安全性共享。使用不可变对象线程安全免费。你可以做如下的事情。您可以将PriceCategory作为enum或某个不可变对象。由于enum本质上是不可改变的,因此我们可以将对象创建占用空间最小化并且也是安全的。

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 
} 
}