This section briefly describes the hierarchical design concept in Java. As shown in:
The function implementation is divided into two layers: the access layer and the business layer.
(1) design the IDao Interface
package web.java.xml.model;public interface IDao {public void create();}
(2) design the interface implementation class DaoJdbc
package web.java.xml.model;public class DaoJdbc implements IDao {@Overridepublic void create() {System.out.println("DaoJdbc::create()");}}
(3) design the interface implementation class DaoHibernate
package web.java.xml.model;public class DaoHibernate implements IDao {@Overridepublic void create() {System.out.println("DaoHibernate::create()");}}
(4) design the singleton Factory
Package web. java. xml. model;/*** Singleton Dao Factory: * Singleton Mode features: * (1) Singleton class can only have one instance * (2) the Singleton class must create a unique instance for itself * (3) the singleton class must provide this instance to all other objects */public class DaoFactory {// 1. private constructor. You cannot create private DaoFactory () {} // 2 for external objects. this class must automatically provide this instance object public static DaoFactory getDaoFactory () {if (daoFactory = null) {daoFactory = new DaoFactory ();} return daoFactory ;} // 3. the Singleton class must execute the creation of private static DaoFactory daoFactory; public IDao getDao () {// The project always modifies the content here as needed, determine what kind of product the factory provides return new DaoJdbc ();}}
(5) design the Business Layer
Package web. java. xml. model;/*** business layer **/public class Service {public void create () {DaoFactory daoFactory = DaoFactory. getDaoFactory (); IDao iDao = daoFactory. getDao (); iDao. create ();}}
The implementation of the business layer function depends on the factory to provide products externally. The implementation of the factory depends on the following data access layer code. The hierarchical design helps code refinement and facilitate later updates and maintenance.
(6) compile test functions
package web.java.xml.model;public class Demo1 {public static void main(String[] args) {Service ser = new Service();ser.create();}}
Obviously, if you want any product here, you only need to modify the corresponding code in the factory.