This afternoon, we mainly studied the templatemethod in the design mode (mode design pattern).
In spring, various o/rm are encapsulated, such as the Hibernatetemplate package for hibernate, and JdbcTemplate encapsulation for JDBC. These packages all practice the Template Method design pattern.
For Hibernatetemplate, spring encapsulates the transaction management of hibernate through this class.
/* This post is intended to simulate the implementation of the Hibernatetemplate, which is spring's encapsulation of hibernate operations transactions, using the template method design pattern */ /* *//**/
Directly on the code:
1. Interface:
Public Interface Myhibernatecallback { publicvoid Doinhibernate (Session session);}
2. Myhibernatetemplate
Public classmyhibernatetemplate {@AutowiredPrivatesessionfactory sessionfactory; /*simulation of the implementation of Hibernatetemplate, which is spring's encapsulation of hibernate operations transactions, using the template method design mode*/ /*when the execution of many methods has a large number of repetitive code (such as the processing of transactions), it is possible to consider extracting the fixed parts and different parts into the form of interfaces, together to form a method*/ /*Add different business logic to the method by implementing the interface form*/ /*Common Code Body*/ Private voidexecutewithsession (Myhibernatecallback callback) {Session session=NULL; Try{Session=sessionfactory.opensession (); Session.begintransaction (); /*different, the interface is extracted according to the context*/Callback.doinhibernate (session); Session.gettransaction (). commit (); } Catch(RuntimeException e) {e.printstacktrace (); if(Session! =NULL) {session.gettransaction (). rollback (); } } finally { if(Session! =NULL) {session.close (); } } } Public voidSaveFinalUser User) { /*implementing interfaces through internal classes*/Myhibernatecallback CallBack=NewMyhibernatecallback () {@Override Public voidDoinhibernate (Session session) {Session.save (user); } }; Executewithsession (CallBack); }}
3. Call:
Public class Implements Userdao { @Resource private myhibernatetemplate myhibernatetemplate; @Override publicvoid Save (User user) { myhibernatetemplate.save ( user); A sentence to be done! }}
To be honest, it's important to think!
Design mode-Template Method