日期:2014-05-16 浏览次数:20477 次
public abstract class TemplatePattern { //模板方法 public final void templateMethod(){ method1(); method2();//勾子方法 method3();//抽象方法 } private void method1(){ System.out.println("父类实现业务逻辑"); } public void method2(){ System.out.println("父类默认实现,子类可覆盖"); } protected abstract void method3();//子类负责实现业务逻辑 }
public class TemplatePatternImpl extends TemplatePattern { @Override protected void method3() { System.out.println("method3()在子类TemplatePatternImpl中实现了!!"); } }
TemplatePattern t1 = new TemplatePatternImpl(); t1.templateMethod();
父类实现业务逻辑 父类默认实现,子类可覆盖 method3()在子类TemplatePatternImpl中实现了!!
public class TemplatePatternImpl2 extends TemplatePattern { @Override protected void method3() { System.out.println("method3()在子类TemplatePatternImpl2中实现了!!"); } /* (non-Javadoc) * @see com.jak.pattern.template.example.TemplatePattern#method2() */ @Override public void method2() { System.out.println("子类TemplatePatternImpl2覆盖了父类的method2()方法!!"); } }
TemplatePattern t2 = new TemplatePatternImpl2(); t2.templateMethod();
父类实现业务逻辑 子类TemplatePatternImpl2覆盖了父类的method2()方法!! method3()在子类TemplatePatternImpl2中实现了!!
public List<User> query() { List<User> userList = new ArrayList<User>(); String sql = "select * from User"; Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = HsqldbUtil.getConnection(); pst = con.prepareStatement(sql); rs = pst.executeQuery(); User user = null; while (rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUserName(rs.getString("user_name")); user.setBirth(rs.getDate("birth")); user.setCreateDate(rs.getDate("create_date")); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); }finally{ if(rs != null){ try { rs.clo