ALBERLAU blog

Blog about my personal experience in software development.

Tuesday, March 10, 2009

 

Decorating list objects dynamically to display calculated fields

Imagine there is Account class that holds IBAN, currency, and balance. Customer wants to display combo of accounts that displays options in format LT025010200020000141 LTL(1000.23) . Most quick solution probably is to place :

getDisplayInFormat1() { return iban+" "+currency+"("+balance+")";}

method inside of Acount class. Of course Account class will soon be overwhelmed with getDisplayInFormat2, getDisplayInFormat3 and so on methods with view related information, possibly with style:red to indicate insufficient balance.

Next solution is to create some DropDownAccountDecorator. Usage is below:




List<Account> acc = cpFacade.loadAccounts(user);
List decoratedAcc = ListDecorator.getInstance(new DropDownAccountDecorator(), acc);




DropDownAccountDecorator source :



import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class DropDownAccountDecorator implements IListItemDecorator,Serializable {
private boolean hideBalance;

@Override
public Object decorate(final Object o) {
return Enhancer.create(o.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method mth, Object[] args, MethodProxy mpx) throws Throwable {
Object res = mth.invoke(o, args);
String mname = mth.getName();
if (!mname.equals("getDisplay")) {
return res;
}
Account acc = (Account) obj;
String display;
if (AccStates.BLOCKED.equals(acc.getAccState())) {
display = String.format("%s (%1.2f %s blocked)", acc.getName(), acc.getTotalBalance(), acc.getCurrencyDetail().get(0).getCurrency().getCode());
} else {
if(hideBalance) {
display =  String.format("%s %s", acc.getName(), acc.getCurrencyDetail().get(0).getCurrency().getCode());
} else {
display = String.format("%s (%1.2f %s)", acc.getName(), acc.getTotalBalance(), acc.getCurrencyDetail().get(0).getCurrency().getCode());
}
}
return display;
}
});
}

public void setHideBalance(boolean b) {
this.hideBalance=b;
}
}




Code uses ListProxy infrastructure from my previous post.
Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

January 2008   February 2008   March 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]