• Welcome to KonaKart Community Forum. Please login or sign up.
 

Customizing KonaKart Product bean

Started by jeffzzang, March 04, 2009, 09:43:46 pm

Previous topic - Next topic

jeffzzang

I want to extend the functionality of the com.konakart.app.Product bean so that it contains an additional method called getBriefDescription() which basically returns the description of the product, truncated to 20 characters. My first idea was to extend the Product bean as follows:


public class MyProduct extends Product {

  public String getBriefDescription(){

if (this.getDescription().length() > 20){
return this.getDescription().substring(0,20) + "...";
}
                else{
       return this.getDescription();
               }

}
}


Using this technique, MyProduct contains all the same methods as Product and adds one additional method (getBriefDescription()). However, when I try to use this bean in the following code:


//get all the products from the db - the products will NOT be populated
ProductIf[] prodArray = kkEng.searchForProducts(null, null, productSearch, -1).getProductArray();

//populate each product
for (int x = 0; x < prodArray.length; x++){
  MyProduct myP = (MyProduct)kkEng.getProduct(null,prodArray[x].getId(),-1));
}


This throws a run-time ClassCastException because I am downcasting from Product to MyProduct.

My second thought is to use the Decorator pattern which essentially wraps the Product bean and adds the getBriefDescription() method:


public class ProductDecorator extends Product {

protected Product p;

public ProductDecorator(Product p){
this.p = p;
}

public String getBriefDescription(){

if (this.p.getDescription().length() > 20){
return this.p.getDescription().substring(0,20)+"...";
}
return this.p.getDescription();

}
}


Then in the code that gets the products from the db:


//get all the products from the db - the products will NOT be populated
ProductIf[] prodArray = kkEng.searchForProducts(null, null, productSearch, -1).getProductArray();

//populate each product
for (int x = 0; x < prodArray.length; x++){
  ProductDecorator myP = new ProductDecorator((Product)kkEng.getProduct(null,prodArray[x].getId(),-1)));
  ...add it to the collection that will be returned...
}



The only issue I have with this technique is that I can't use ProductDecorator exactly like a Product without having to implement ALL the methods of Product like so:


public String getName(){
return this.p.getName();
}
public BigDecimal getPriceExTax(){
return this.p.getPriceExTax();
}
public BigDecimal getPriceIncTax(){
return this.p.getPriceIncTax();
}

        ..etc..


Does anyone know any good techniques to try to do what I'm doing?