190 likes | 204 Views
Discover the Template Pattern in Java design, its structure, and implementation with examples outside the Java arena. Learn how to apply this pattern with best practices and associated technologies.
E N D
AJAX! KC Web & Java 29 november 2005
J2SE Design Patterns:Het Template Pattern Lucas Jellema KC Web & Java – 10 Minute Talks,Donderdag 29 november 2005
Introducing Design Patterns • Recurring algorithms, construction, designs • Best practices • Associated with various technologies • ERD • Database Design • J2EE Architecture • MVC, Business Delegate, Façade, … • Non IT environments • J2SE – Java Programming • Most famous: …. • Singleton
Great Book: Head First Design Patterns • Observer • Decorator • Factory • Singleton • Command • Adapter and Façade • Iterator and Composite • State • Proxy • Compound
The Template Patternaka Don’t Call us, We will call You! TeaMaker CoffeeMaker CoffeeVerkeerdMaker • getCup • boilWater • steepTeaBag • pourInCup • optional addSugar • optional addLemon • getCup • boilWater • brewCoffee • pourInCup • optional addSugar • optional addMilk • getCup • boilWater • brewCoffee • pourInCup • addMilk • optional addSugar Generic pattern • getCup • boilWater • brew WHATEVER • pourInCup • addCondiments
The Template Pattern • The Template (Method) Pattern • Defines the skeleton of an algorithm in a method, deferring some steps or pieces to sub-classes • Lets subclasses (re)define part of an algorithm without changing its structure (abstract) superclass final abstract algorithm hook (concrete) subclass (concrete) subclass
The Template Pattern • The Template (Method) Pattern • Three modes • Forcing subclasses to implement certain steps (abstract or interface) • Allowing subclasses to complement certain steps (through overridable hooks) • Allowing subclasses to redefine steps (through overridable algorithm methods) • Non-overridable steps are defined final in the superclass
Using the Template MethodMy Little Coffeshop package nl.amis.shop.mypackage; public class CoffeeShop { public CoffeeShop() { } public void drinkBeverage( BeverageMachine bm) { bm.prepareRecipe(); System.out.println("Enjoy your drink\n"); } public static void main(String[] args) { CoffeeShop coffeeShop = new CoffeeShop(); coffeeShop.drinkBeverage(new CoffeeMachine()); coffeeShop.drinkBeverage(new TeaMachine()); coffeeShop.drinkBeverage(new CoffeeWrongMachine()); }//main }
Examples of the Template (Method) PatternDon’t Call Us – We Will Call You • Spring JDBC • Arrays.sort(Object[] a) • Not a Superclass/Subclass situation • To use sort on an array, the array elements must implement the Comparable interface • by defining the compareTo() method • java.io.InputStream – abstract read() method that subclasses must implement • Swing • JFrame – paint() method: a hook with an empty default implementation • Applet – start(), stop(), destroy(): hooks • ADF DataAction • override onCommit, add onMyEvent
Examples of the Template (Method) PatternOutside the Java Arena • Oracle Forms event-triggers • Pre-Insert, Post-Insert – hooks surrounding the Insert algorithm • even On-Insert that allows overriding of the core of the the Insert algoritm • but even then the other hooks will exist • Database DML Event Triggers • Before insert statement, before insert row • After insert row, After insert statement
Architectuur Domain Object Domain Object Domain Object JNDI Service DAO
Example private Connection getConnection() throws SQLException { try { DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); return DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:orcl“ ,"scott", "tiger"); } catch (SQLException sqle) { // handle exception return null; } } import java.sql.*; import javax.sql.*; public class EmpDao { public List getAllEmployees() { Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List emps = new ArrayList(); try { con = getConnection(); pstmt = con.prepareStatement ("select * from emp"); rs = pstmt.executeQuery(); while (rs.next()) { Employee e = new Employee(); e.setId (rs.getLong(1)); e.setName (rs.getString(2)); // ... emps.add(e); } } catch (SQLException e) { // handle exception } finally { try { rs.close(); pstmt.close(); con.close(); } catch (SQLException e1) { // no action needed } } return emps; } } private Connection getConnection() throws SQLException { try { Context ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup ("java:comp/env/jdbc/myDatabase"); return ds.getConnection(); } catch (NamingException e) { // handle exception return null; } }
Template Pattern • Operation largely follows a standard algorithm • At certain steps, specialization or customization is required • Several implementations • Abstract ‘hook’ methods that sub-class may override • Parametrize behaviour and have invoker provide the details • Such as the SQL Query • Spring JDBC Templates • Implement all JDBC wiring • Parametrize the query and the result-handling
Example of Spring JDBC Template public interface empDao { public List getAllEmployees (); } public class EmployeeJdbcDao extends JdbcDaoSupport implements EmpDao { public List getAllEmployees() { JdbcTemplate jt = getJdbcTemplate(); return jt.queryForList (“select * from emp”); } } <bean id="dataSourceDBDirect" class="org.springframework.jdbc.datasource.DriverManagerDataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:BAARSJES1" /> <property name="username" value="scott" /> <property name="password" value="tiger" /> </bean> <bean id="employeeDAO" class="nl.amis.demo.dao.jdbc.EmployeeJdbcDao" > <property name="dataSource"> <ref local="dataSourceDBDirect" /> </property> </bean>
Conclusions • Template Method Pattern • Instead of overriding and reimplementing the algorithm in a subclass • The algorithms has predefined call outs • To abstract method that subclasses MUST implement • To concrete, overridable methods to change parts of the algorithm – but not the overall structure! • To hooks (optionally implemented by subclasses to complement the steps of the algoritm • Easy to apply • Recognized from duplication of algorithm across classes • You frequently override a method and duplicate most of its implementation • Read – and enjoy – Head First Design Patterns