Application of design pattern in EJB

zhaozj2021-02-16  172

Board bridge http://www.jdon.com 2002/05/06

What is a design pattern design pattern is a set of repeated use, most people know, classified catalog, code design experience. The use of design patterns is for reusable code, so that the code is easier to be understood by others to ensure code reliability.

There is no doubt that the design model is more than the system, the design model makes the code real engineering, the design model is the cornerstone of the software engineering, just like a block of bricks with the building.

GOF's "design mode" is the first time to upgrade the design pattern to the theoretical height, and standardize it, this book proposes 23 basic design patterns, since then, in the development of object-oriented software, new A large number of design patterns continue to appear.

Design patterns and frameworks are now available to object-oriented software systems now generally divided into three major categories: Framework, the specific software we usually develop is an application; Java's API belongs to the toolbox; The framework is a class that constitutes a class of collaborative classes that can be multiplexed for a particular software. EJB (Enterprise JavaBeans) is a framework for Java applications to enterprise computing.

The framework usually defines the design parameters of the overall structural classes and objects of the application system, so that the specific application implementors can concentrate specific details of the application itself. The framework mainly records common design decisions in software applications, and the framework emphasizes the design multiplexing, so the design mode must be used in the frame design.

In addition, the design pattern helps to understand the framework structure, the mature framework usually uses a variety of design patterns, if you are familiar with these design patterns, there is no doubt that you will quickly master the framework of the frame, and we generally developers EJB J2EE and other frameworks, it will feel particularly difficult, difficult to master, then keep the design model first, which is undoubtedly a tool for you to analyze the EJB or J2EE system.

Design Mode in EJB Under Take a look at the EJB framework from the angle of design mode? Before this, you have probably understand the design model. Special design patterns explain, please see my design pattern.

EJB is a multi-layer structure, the original database development is basically the application (commercial logic operation) directly calls the database driver, in EJB, in order to complete the business logic calculation and database, use multiple structural modes: Adapter mode and Bridge mode Wait. The benefits of doing this obviously three:

1. The commercial logic layer and data access layer are separated; 2. Multiple databases can be supported simultaneously; 3. Database type replacement, it is not designed to a large number of commercial logic code.

The Database is called the database (such as a SELECT, etc.), and the corresponding database is called a recorded bean called entity bean; completed by these two types of beans. Access.

Session beans are generally related to client applications, and the database end is closely related to entity beans, EJB uses Adapter mode and Bridge mode between entity beans and database, unintentional in entity bean There are also a layer between the database, called DAO (Data Access Object), DAO is actually a mixture of design modes.

We take Catalog in Java as an example, which is a pet category specifically dealing with pet stores. In database access, there are two major procedures: Catalogjb and CatalogDao, we look at the design pattern from specific code. Applied.

Bridge mode and adapter mode We first take a look at CatalogEJB code:

public class CatalogEJB implements SessionBean {protected CatalogDAO dao; // DAO obtained from a plant which is one example of DAO public void ejbCreate call factory (Factory) Mode () {try {dao = CatalogDAOFactory.getDAO ();} catch (CatalogDAOSysException SE) {debug.println ("Exception getting Dao" se); th.getMessage ());}} ....} We found that there is no usual session bean in Catalog Bean to operate. SQL operation statements such as "select .. from.", These are all encapsulated into the specific implementation of DAO (Concrete Class).

In the case of Catalog, the Bridge mode of design mode is used. It is determined whether it is a model, mainly according to its participant's type and interrelationship, let's take a look at the definition and participants of Bridge mode:

The Bridge mode is divided into abstraction and behavior, each independent, but can be dynamically combined (as if built a bridge). In this example, it is to open such behavior to the business logic and database, and the database access is specifically placed in DAO.

Bridge mode requires two interfaces (abstract classes and interfaces are met), one is used to encapsulate abstract parts, in this example, packaging business logic, is CatalogGejb; there is a package behavior (IMPLEMENTOR), this example is CatalogDao, this example is CatalogDao, this example is CatalogDao, this example is CatalogDao, Take a look at CatalogDao code:

public interface CatalogDAO {public Category getCategory (String categoryID, Locale l) throws CatalogDAOSysException; public Page getCategories (int start, int count, Locale l) throws CatalogDAOSysException; public Product getProduct (String productID, Locale l) throws CatalogDAOSysException; public Page getProducts ( String categoryID, int start, int count, Locale l) throws CatalogDAOSysException; public Item getItem (String itemID, Locale l) throws CatalogDAOSysException; public Page getItems (String productID, int start, int size, Locale l) throws CatalogDAOSysException; public Page searchItems String query, int start, int size, local l) throws catalogdaosysexception;

Participants in Bridge mode also need a specific implementation of behavioral interfaces, in this case, CatalogDaoImpl, although there is only one ConcreteImplementor in the current pet store, but can be extended to mysql XML and other data source access, such as you can yourself Added a subclass called CatalogDaoImplmysql and as a CatalogDao.

See CatalogDAO a subclass CatalogDAOImpl code: public class CatalogDAOImpl implements CatalogDAO {protected static DataSource getDataSource () throws CatalogDAOSysException {try {InitialContext ic = new InitialContext (); return (DataSource) ic.lookup (JNDINames.CATALOG_DATASOURCE);} Catch (Namingexception Ne) {throw new catalogDaosystem ("Namingexception While" "UP DB Context:" Ne.GetMessage ());}} // The specific SELECT statement appears here, this is mainly the access statement of the Oracle database PUBLIC category getCategory (String categoryID, Locale l) throws CatalogDAOSysException {Connection c = null; PreparedStatement ps = null; ResultSet rs = null; category ret = null; try {c = getDataSource () getConnection ();. ps = c.prepareStatement ( "SELECT A. Catid, Name, Descn" "from" Category_Details B on " " a.catid = b.catid) " " Where local =? " " and a.catid =? ", Resultset.type_scro LL_INSENSITIVE, ResultSet.concur_read_only; ps.setstring (1, l.tostring ()); ps.setstring (2, categoryID); RS = ps.executeQuery (); if (rs.first ()) {Ret = new category (rs.getstring (1) .trim (), rs.getstring (2), rs.getstring (3));}}}}}}}}}}}}}}}}}}}}}}}} @close (); c.close (); return return;} Catch (SQLException Se) {throw new catalogdaosystem ("sqlexception:" se.getMessage ());} ....

Bridge mode participants summarize as follows:

Business logic abstract class (Catalogjb)

Abstract business logic. Calling DAOMPLEMENTOR. Do not care is the specific data source is used (whether Oracle or JDBC is also XML). DAO (Data Access Object) (CatalogDao)

Abstract operation behavior for data sources. API structure that is very convenient to access and maintain management data is provided.

Daoimplementor (CatalogDaoImpl may have CatalogDaoImplsyBase CatalogDaoImplmysql, etc.)

Implement specific DAO interface content. Use Adapter mode to adapt the specific data source driver interface to the DAO interface

Data Source (Oracle, Or Sybase Database Via JDBC API)

Provides a driver interface to access a specific database, such as including a connection pool, and the like.

When using the data source drive interface, you need to use the Adapter mode, and the Adapter mode is used together, and the Adapter mode is actually using a combination (inheritance) to reproduce the class, in the famous "THINK IN JAVA" "class regeneration" is specifically mentioned in these two ways.

Obviously, if you are familiar with Bridge mode and Adapter mode, then the Catalog understanding of the pet store will be very fast, and like, other parts of the pet shop can quickly understand.

Factory mode and Singleton mode This mode is similar to New. It is used to create objects. Using the Factory mode is to achieve object-oriented basic principles. Package (degapsulation); will create objects and use objects. Therefore, in the usual development process, try to create an object using the Factory mode.

This example catalog is a specific instance object for obtaining a DAO using the Factory mode, see the comment in the CatalogEJB code above. Let's take a look at the code of CatalogDaOfactory:

public class CatalogDAOFactory {public static CatalogDAO getDAO () throws CatalogDAOSysException {CatalogDAO catDao = null; try {InitialContext ic = new InitialContext (); String className = (String) ic.lookup (JNDINames.CATALOG_DAO_CLASS); catDao = (CatalogDAO) Class. Forname (classname) .newinstance ();} catch (namingexception ne) {...} return catdao;

In CatalogDaOfactory, based on the system profile, dynamically obtain DAO method, the reason why it takes dynamic approach, of course, it is convenient for users to increase their own DAO mode, without having to modify the code, just modify the configuration file directly.

If you only need CatalogDaOfactory to generate an instance here, you can take the Singleton mode, the purpose of Singleton is to control the creation of class instance objects, and allow the entire program to access it only at a point. Singleton itself can only create one, which is a single thread.

public class CatalogDAOFactory {private static CatalogDAO catDao = null; public static CatalogDAO getIntance () {if (catDao == null) try {InitialContext ic = new InitialContext (); String className = (String) ic.lookup (JNDINames.CATALOG_DAO_CLASS); CATDAO = (CATALOGDAO) Class.Forname (ClassName) .newinstance ();} catch (namingexception ne) {...}}}}}}} then call from DAO = CatalogDaofactory.GetDao (); DAO = catalogdaofactory.getInTance ();

FACADE mode In EJB applications, there are two endpoints, this end is the user, and the other end is EJB, usually in the two end points, which will be increased to loosen the coupling between the two endpoints, such as in a pet shop. In the example, considering users of different identities have different operational processes. For example, after the customer registration, you need to browse the directory, order, and store managers need to confirm or negate orders, or check the stock. These features need to be done with Session Bean and Entity Beans.

But if the client interacts directly with these beans:

1. The user must pay attention to all the contacts or interactive things of these beans, can not prevent the user from using these beans.2. If EJB's API changes, some of the code of the client must be modified. Undoubtedly a poor scalability. 3. Even if these Beans are on the same server, the client is still invoked by the Remote mode, causing the network to be crowded for no reason.

Then we use the Facade mode to solve this problem, Facade definitions provide a consistent interface for a set of interfaces in the subsystem, and it is clear that we need to provide a unified external interface for these beans. As shown below:

In a pet store, ShoppingClientFacadelocaleJB is a unified interface for all user-end operations. User-end operations are not directly connected with those EJBs such as Customerejb or ShoppingCartejb, but are contacted by ShoppingClientFacadelocaleJB. code show as below:

public class ShoppingClientFacadeLocalEJB implements SessionBean {... // CustomerEJB Information and public CustomerLocal getCustomer () throws FinderException {if (userId == null) {...} try {InitialContext ic = new InitialContext (); Object o = ic.lookup ("Java: Comp / Env / EJB / PETSTORE / LOCAL / CUSTOMER"); CustomerLocalHome Home = (CustomerLocalHome) O; Customer = Home.FindByPrimaryKey;} catch (javax.naming.namingexception nx) {...} return customer;} ..... // Information and ShoppingCartEJB public ShoppingCartLocal getShoppingCart () {if (cart == null) {try {InitialContext ic = new InitialContext (); Object o = ic.lookup ( "java: comp / ENV / EJB / CART / CART "); ShoppingCartLocalHome Home = (ShoppingCartLocalHome) O; Cart = Home.create ();} catch (javax.ejb.createexception cx) {...}} return cart;} .... } FACADE Mode Participant:

SessionFacade (ShoppingClientFacadelocalejb)

Provide a set of operational processes to truly delegate to the bean of EJB.

EJB's bean (Customerejb, ShoppingCartejb, etc.)

Executing basic business logic operations There is no call to SessionFacade.

This not only increases the scalability, but also improves the efficiency, the user only needs REMOTE to call the sessionFacade call, and the sessionFacade will automatically locate those neighbors who have the same server bean (Customerejb, ShoppingCartejb, etc.), undoubtedly Reduce the cybercrow, improve the speed.

Summarizing the specific use of EJB, using the appropriate design mode, not only enhanced code reusability, but most importantly, we can improve efficiency and speed, we know that the EJB framework is considered to consider all aspects of transaction security in large systems. The efficiency performance is lacking, then we can make up for this problem when we are applying for specific issues.

For example, PROXY mode provides a proxy when it can be expanded for us to discharmatically, this will not affect the current running speed because of that huge object, and those in EJB will apparently belong to huge objects (because they There are repeated database operations, these are spent.

Flyweight mode is to avoid small costs of small classes with the same content (such as spending memory), so that everyone share a class (category). When you have to get a series of strings from EJB, there must be many of these strings. Duplicate, then we can store these repeated strings in the Flyweight Pool (Pool) to achieve share. This type of application will be introduced in the later space.

The pet shop source URL: http://java.sun.com/blueprints/code/jps13/src/index.html This example can be queried therefrom.

转载请注明原文地址:https://www.9cbs.com/read-8397.html

New Post(0)