场景一:当某个类除了它的外部类,不再被其他的类使用时
场景二:解决一些非面向对象的语句块:try{}catch{}finally{}
public interface DataManager { public void manageData(); }
public class DataTemplate{ public void execute(DataManager dm) { try { dm.manageData(); } catch(Exception e) { LoggerAgent.error("GetHeaderData", "getDivisionData", "SQLException: " + e); e.printStackTrace(); }finally{ manager.close(stmt); manager.releaseConnection(conn); } } }
new DataTemplate().execute(new DataManager() { public void manageData() { String[] divisionData = null; conn = manager.getInstance().getConnection(); stmt = (OracleCallableStatement)conn.prepareCall("{ Call PM_GET_PRODUCT.HEADER_DIVISION(?, ?) }"); stmt.setLong(1 ,productId.longValue() ); stmt.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); stmt.execute(); ResultSet rs = stmt.getCursor(2); int i = 0 String strDivision = ""; while( rs.next() ) { strDivision += rs.getString("DIVISION_ID") + "," } int length = strDivision.length(); if(length != 0 ) { strDivision = strDivision.substring(0,length - 1); } divisionData = StringUtil.split(strDivision, ","); map.put("Division", strDivision ); LoggerAgent.debug("GetHeaderProcess","getDivisionData","getValue+" + strDivision +" " + productId); } });
场景之三:一些多算法场合:
Arrays.sort(emps,new Comparator(){ Public int compare(Object o1,Object o2) { return ((Employee)o1).getServedYears()- ((Employee)o2).getServedYears(); } });
场景之四:适当使用内部类,使得代码更加灵活和富有扩展性
package polyFactory; public interface Shape { public void draw(); public void erase(); } package polyFactory; import java.util.HashMap; import java.util.Map; public abstract class ShapeFactory { protected abstract Shape create(); private static Map factories = new HashMap(); public static void addFactory(String id,ShapeFactory f) { factories.put(id,f); } public static final Shape createShape(String id) { if(!factories.containsKey(id)) { try { Class.forName("polyFactory."+id); } catch(ClassNotFoundException e) { throw new RuntimeException("Bad shape creation : "+id); } } return ((ShapeFactory)factories. get(id)).create(); } }
package polyFactory; public class Circle implements Shape { public void draw() { System.out.println("the circle is drawing..."); } public void erase() { System.out.println("the circle is erasing..."); } private static class Factory extends ShapeFactory{ protected Shape create() { return new Circle(); } } static {ShapeFactory.addFactory("Circle",new Factory());} }
package polyFactory; public class Square implements Shape { public void draw() { System.out.println("the square is drawing..."); } public void erase() { System.out.println("the square is erasing..."); } private static class Factory extends ShapeFactory { protected Shape create() { return new Square(); } } static {ShapeFactory.addFactory("Square",new Factory());} }