设计模式之责任链2
使用责任链模式进行类型转换
public class Test {
public static void main(String[] args) {
Date d = new Date();
Double d2 = new Double("99.145456");
String str = null;
FormaterChain fc = FormaterChain.getInstance();
fc.add(new DateFormater());
fc.add(new DecimalFormater());
//转换日期
str = fc.doFormat(d);
System.out.println(str);
//保留小数2位
str = fc.doFormat(d2);
System.out.println(str);
}
}
//对象转字符串
public interface Formater {
String format(Object o, FormaterChain chain);
}
//单例、责任链
public class FormaterChain {
private List<Formater> formaters = new LinkedList<Formater>();
private Iterator<Formater> chain = null;
private FormaterChain(){}
private static class Inner{
private static FormaterChain formaterChain = new FormaterChain();
}
public static FormaterChain getInstance(){
return Inner.formaterChain;
}
public String doFormat(Object o){
if(o == null){
return null;
}
if(chain.hasNext()){
Formater f = chain.next();
return f.format(o, this);
}
return o.toString();
}
//增加类型转换器
public void add(Formater f){
formaters.add(f);
chain = formaters.iterator();
}
}
//日期转换器-转换为字符串
public class DateFormater implements Formater {
public String format(Object o, FormaterChain chain) {
if(o.getClass().equals(java.util.Date.class)){
return date2str((java.util.Date)o);
}
return chain.doFormat(o);
}
private String date2str(Date d){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(d);
}
}
public class DecimalFormater implements Formater {
public String format(Object o, FormaterChain chain) {
if(o.getClass().equals(java.lang.Double.class)){
return double2str((Double)o);
}
return chain.doFormat(o);
}
private String double2str(double d){
DecimalFormat df = new DecimalFormat("0.00");
df.setRoundingMode(RoundingMode.HALF_UP);
return df.format(d);
}
}