Session Facade rules and patterns

zhaozj2021-02-16  157

Kyle Brownjava performs designers, IBM WebSphere Service 2001 In the past few years, Enterprise JavaBeansTM (EJB) did have begun to have an impact on JavaTM object design. During the period, one of the most commonly used EJB patterns we see is the session facade concept. This is a strong and very simple concept that makes many developers benefit from both a lot. However, I also see that there is still a lot of misunderstandings for the exact meaning of this model and its application in practice. In order to tell this question more, I will tell some of the basic concepts of Facade and the working mechanism of the Session Facade model, and discuss some of the problems derived from this pattern. I hope to clarify some misunderstandings and help developers use this model correctly. What is session facade? Why do you need it? Many places have a clear description of the Session Facade mode, that is, [Sun 2001] and [Brown 2000]. I don't want to copy all the content there, and I plan to summarize it here: Basic issues are in EJB clients (eg, Servelet, Java applications, etc.) cannot directly access Entity Beans. Thus, there are several reasons:

The performance of the running state when relying on the RMI-IIOP, the performance of the state, is greatly affected. If the client requests an Entity Bean to indicate a bank account that contains two data (in the name of the account balance and account owner name), two network calls will be required. When a large number of attributes make network calls to increase, these overheads will become very obvious. [Monson-Haefel] may be a solution that is a solution that the so-called bulk accessor is some of the methods on the Entity Bean, which creates and returns the value object to represent the data in the Entity Bean. It is actually a solution adopted by Java VisuaLage® CopyHelper Access Beans. However, it has an unfortunate defect, which is that it assumes that all requests need "all" data in EJB, and the result returns some unnecessary data and leads to organization and decomposition of larger value objects. An additional overhead is generated. More importantly, if you allow the EJB client to access the Entity Bean directly, the client is required to understand the internal method of the Entity Bean, which has exceeded the scope of the client's cash. For example, operating an Entity Bean requires the relationship (association, inheritance) of the entity involved, so that all the details of the business model are not appropriately exposed to the client. In addition, how many Entity Beans will require the use of client transactions - this is another factor that complicates things, which means that EJB may be removed from the client design instead of adding. Most designers have found that in order to avoid direct access to Entity Beans in EJB design, they can be found in the Facade described in [Gamma]. [Gamma] This describes the FACADE mode: "Provides a unified interface for a set of interfaces in the subsystem. FACADE defines a higher level of interface that makes the subsystem easier." 1 Apply this idea in EJB Typically, you should create a session ejb that acts as a Facade, and then puts a set of Entity Beans that make up the subsystem. In this way, the client is separated from the details of the Entity Bean, and does not have to manage the details of transaction management. But the problem is that there are many people who will stop. Then they easily do it down, starting the Entity Bean into the session bean, regardless of the other content described in the Facade mode and the problem derived from the Facade mode in the EJB design. This is probably due to the truth of the "second-hand" information of the obtained Facade, and did not study the original mode. If we have spend some time to understand the problem of Facade derived, we will see more beneficial design possibilities inherent in this mode. The key points of the FACADE mode we should understand are described in the key point of the FACADE mode. The previous point can be found in the "Applicability" description section of the FACADE mode. It describes what the mode you need to apply. They are: "When you want to provide a simple interface for complex subsystems ... Please use Facade mode" and "When you want to hieraries subsystems ... Please use Facade mode. Using Facade for each layer system Define an entry point. "2 From the discussion of the FACADE mode, we can extract two views. The first point is that Facade should provide an abstract view of the subsystem, rather than simply packaging the entire subsystem itself.

Unfortunately, I have seen the session bean created by developers many times in the actual plurality of session beam all the ways of the Entity Bean Home and the Entity bean objects, not any extra abstraction, which is the most evil abuse of this model. One of the cases. Keep in mind that this idea is to reduce the complexity of the entire system, rather than transferring complexity to another object. The second point is also a little more subtle, related to the layering. This point of view believes that you can hide the details of the next subsystem with multiple Facade. Therefore, here you can imagine that Session Facade should be on the other Facade, the top layer is further abstraction of the underlying business logic details. This is critical. When you read two of the following two (from [Gamma] Con Constraising, "Collaboration" and "Related Mode" section) are described, this will be more clearly cleared: "The client will send the request to Facade, and then FACADE forwards the request to the appropriate subsystem object to communicate with the subsystem. "3" FACADE is only abstracted to the interface to the subsystem object to make them easier to use; it does not define new features. "4 I put these The point summary is as follows: Facade does not do the actual work of the system; but entrusts other objects to do this. This in reasoning that you must place these objects correctly so that this mode can be run according to your expectation. This is the main difference between the two epidemic expressions [Sun 2000] and [Sun 2001] in this mode. The first version, ie [Sun 2000] is part of the J2EE plan, which refers to this model as "session entity facade". It is intended to "provide a single interface" for a bunch of enterprises Beans. It describes such a model that all data access is done by Entity Bean, and the session bean provides interfaces for these Entity Beans. The current question is [Sun 2000] Not necessarily to be centered on EJB. It does not involve other object types and assumes that only EJB objects in the system are assumed. Based on my experience, I think this will lead to a bloated session object that is not reused between the engineering, and in the same project, there is a problem when the demand will have a problem. Now, [Sun 2001] is more common, and there is no problem in the above problems. It simply refers to this model "Session Facade". Its solution requires you to "use the session bean as a FACADE to encapsulate the complexity of the interaction between the business objects of the workflow." It does not limit your business object at all, it should be EJB, so it is a more flexible approach. Session Facade's important rules so how should we apply these rules about the FACADE for the session? What does this mean about our EJB design? I follow three basic principles when I design Session Facade:

They don't do actual work; they delegate other objects to do actual work. This means that each method in Session Facade should be small (the abnormal processing logic is not calculated, the code should be five elements or less). They offer a simple interface. This means that the number of FACADE methods should be relatively small (only about 24 in each session bean). They are the client interface of the underlying system. They should be encapsulated in the subsystem, and should not be disclosed without unnecessary. So what about its working mechanism? What types of objects do you have to age? What benefits will this bring to your design? In my early papers and [Brown 2001], I have discussed some of these problems where some details can be found. However, in general, in my majority EJB design I usually find the following four types of objects: Value object is the data containing the data requested by the client. It contains a subset of the data contained in the Entity Bean and other data sources. It is the return type of the Session EJB method. [EJB 2.0] and [SUN 2001] are used to describe the use of value objects and value objects. Note [Fowler 2001], it is called "Data Transfer Objects", [Brown 1999] also uses this name. I personally think that the data transfer object is a better descriptive term, but unfortunately, Sun's term seems to be more common. Object Manufacturing [Brown 1999] [Brown 2000] Responsible for building value objects. It can complete discrimination of different data sources, creating instances of values ​​objects, instances of filling values ​​objects. Each Factory class can retrieve data from multiple data sources or update the data. In your object model, each "root" object should have a Factory class. (Root objects are those "Objects containing" Other objects.) In a sense, the object Factory class acts in the JDBC or lasting Entity Bean subsystem as a hierade in [Gamma]. Entity EJB should be a standard, data source. Entity Beans should not contain an application-specific domain logic, and should not be limited to work within a single application. Note that Entity Bean is optional, it is not necessary in this architecture; Factory may simply obtain data from the data source as a JMS queue or JDBC connection. The Action object is the only object that the session bean may be called by the commercial service. The Action object only processes business processes that are not related to simple creation, read, update, or delete data. Like the object Factory, the Action object also acts as the inner layer Facade. An EJB Object Example Describes a problem with such a mode is that an example that can use this mode is too large, so that it cannot be included in the description of the mode itself. Despite this, I still have to try to mention the following example (it is obviously very simple), clear what these objects look like. Suppose we are building an ATM system for banks. This is one of the oldest OO design issues. Of course, many other books and papers have discussed it, but it does have enough interest in compliance with our request. Through analysis, we found two EJBs.

Connections from ATM to banks are represented as session beans. There are some ways to deal with the transactions that you can complete through ATM - deposit, withdrawal, and account transfer between accounts. The account is expressed as entity bean (our examples use CMP, but it does not actually affect in our example). It has a returning account balance, a method of lending the account. The remote interface of the ATM session bean is as follows: package com.ibm.bankexample.ejbs;

Import com.ibm.bankexample.domain. *;

/ **

* This is The Enterprise Java Bean Remote Interface

* for the ATM EXAMPLE.

* /

Public interface ATM EXTENDS JAVAX.EJB.EJBOBJECT {

Void Deposit (java.lang.string AccountNumber, Double Amount)

Throws java.rmi.remoteexception,

com.ibm.bankexample.domain.factoryException;

Java.util.Vector getaccounts (java.lang.string userid)

Throws java.rmi.remoteexception,

com.ibm.bankexample.domain.factoryException;

Void (Java.lang.String fromaccount, Java.lang.String toaccount, Double Amount)

Throws java.rmi.remoteexception,

com.ibm.bankxample.domain.insuffectientfundSexception,

com.ibm.bankexample.domain.factoryException;

Void withdraw (java.lang.string Accountnumber, Double AMOUNT)

Throws java.rmi.remoteexception,

com.ibm.bankxample.domain.insuffectientfundSexception,

com.ibm.bankexample.domain.factoryException;

}

Similarly, the remote interface of the account EJB is as follows:

Package com.ibm.bankexample.ejbs;

/ **

* This is The Enterprise Java Bean Remote Interface

* for the account entity ejb.

* /

Public interface account extenship javax.ejb.ejbobject {

Void deposit (double amount) throws java.rmi.remoteexception;

Java.lang.string getaccountnumber () throws java.rmi.RemoteException;

Double getBalance () throws java.rmi.remoteexception;

Java.lang.string getUserid () throws java.rmi.remoteexception;

Void setBalance (double newvalue) throws java.rmi.remoteexception;

Void setUserid (java.lang.string newuserid) throws java.rmi.remoteexception;

Void withdraw (double amount) throws java.rmi.remoteexception;}

Now, we have also found that there are two other object types are useful to our system. The first is to describe the value object of the account information displayed on the ATM machine. This class looks like this:

Public Class AccountValue Implements java.io.serializable {

Private java.lang.String Accountnumber;

PRIVATE DOUBLE balance;

}

Of course, the AccountValue class also has a method of getter and setter as an attribute, but we don't think about them temporarily. Now, we basically have enough information to understand the implementation of the getAccounts () method of the ATM EJB. The implementation of this method is as follows:

Public Java.util.Vector getaccounts (String Userid) throws factoryException {

AccountFactory Fact = New AccountFactory ();

Vector result = fact.getaccounts (userID);

Return Result;

}

This method shows the standard mode of the method of the Session Facade EJB. It finds a suitable help object (Action or Factory, in this case, Factory), calls the service method on the object, and then returns the result. If this method is pointed out, we need an AccountFactory class to build Accents from Accounts. This class is defined as follows:

Public class accountfactory {

Private static accounthome accountHome = NULL;

}

The implementation of AccountFactory's getaccounts (userid) method is as follows:

Public Java.util.Vector getaccounts (String Userid) throws factoryException {

Try {

Vector vect = new vector ();

Accounthome home = getaccouneromE ();

Enumeration AccountRefs = Home.FindbyUserId (userID);

While (AccountRefs.hasMoreElements ()) {

Account ACC = (Account) AccountRefs.nexTelement ();

AccountValue ValueObject = new accountValue ();

ValueObject.setAccountnumber

Acc.getaccountnumber ());

ValueObject.setbalance (Acc.getBalance ());

Vect.addelement (ValueObject);

}

Return vect;

} catch (exception e) {

Throw new factoryException

"Cannot Generate Accounts Due to Wrapped Exception" E);

}

}

This method uses a cache an AccountHome instance, which is obtained from the following method:

Private AccountHome getAccounene () {

IF (AccountHome == Null) {TRY {

Java.lang.object HomeObject = GetInitialContext (). Lookup

"COM / IBM / BANKEXAMPLE / EJBS / Account");

AccountHome =

(AccountHome) javax.rmi.portableremoteObject.narrow

(org.omg.corba.object) HomeObject,

AccountHome.Class;

} catch (exception e) {

// Error getting the home interface

System.out.println (

"Exception" E "In CreateTimeSheetHome ()");

}

}

Return AccountHome;

}

As described in [Brown 2001] and [Gunther 2000], in WebSphere®, the cache EJB Home is an excellent habit, because get JNDI InitialContext and get EJB HOME from INITIALCONTEXT for a while. Since you have seen the session, entity and factory together, let's take an example of an Action class. In this example, we have a Transfer object that handles fund transfer from an account to another account. Transfer is created in the implementation of the Transfer () method in the ATM EJB, the implementation of this method is as follows:

Public void transfert (String fromaccount, String toaccount, Double Amount)

Throws insufficientfundsexception, factoryexception {

Transfer trans = new transfert;

Trans.Transfer (fromaccount, toaccount, amount);

}

Please pay attention to the same process again. However, this method does not have to return a value from the Action object. The TRANSFER class is as follows:

Public class transfer {

Private static accounthome accounthome;

}

The implementation of the transfer () method is as follows:

Public void Transfer (String fromaccount, String toaccount,

Double Amount) throws insufficientfundSexception, FactoryException {

Try {

Account from = getaccounthome (). FindbyPrimaryKey

New AccountKey (fromaccount);

Account to = getaccounthome (). FindbyPrimaryKey

New AccountKey (Toaccount);

IF (from.getbalance ()

Throw new insufficientfundSexception ();

TO.DEPOTI (Amount);

From.withdraw (amount);

} catch (exception e) {

Throw new factoryException

"Cannot Perform Transfer. Nested Exception IS" E);

}

}

You have seen the TRANSFER () method in the Transfer object handles the following details: Turn two Account entities, make sure the "from" account has sufficient balance, put the transfer amount into the "to" account, from the "from" account Transfer amount. Similarly, you can see other methods of Action objects to implement other business rules in your system. The reason for using the EJB object then why do we need this second layer object? Isn't we transferring things easier from Corba and RMI to Enterprise Javabean? Why don't you put all the logic in EJB? There are several reasons for this. The first is also the most important reason is that this is a hierarchical application. Placing too much work in a single object is never a good idea. If you use this way to arrange objects called by EJB, you can bring the following benefits:

Place your work in a set of objects on a session layer, allow us to test them easier to independently, perhaps, may even test it outside the J2EE application server environment. Different multiple Session Facade objects can use objects on the same layer without worrying about incorrect transaction semantics, and there is no network and data organization / data decomposition overhead across the session bean. The second layer object allows you to achieve diversification for those objects (by using the Stragtegy mode described in [Gamma]), which can utilize the unique features of the application server while still maintaining the portability of the application server between application servers. For example, [Brown 2000A] describes some special cache policies to improve the performance of EJBs that can work under WebSphere Application Server (Advanced) and cannot work with IBM CICS EJB. By providing two implementations for the same FACTORY class or Action class, you can maintain the entire design of portability, while also utilizing the unique features of each server. In the case where you don't need a JTA transaction (for example, you only operate a single data source), this mode allows you to choose to deploy and build or without EJB applications. For example, in some simple queries, in order to avoid the overhead of the EJB call, you can call Factory directly from the servlet, which can significantly improve efficiency. At the same time, by reviewing several projects, we have found that reuse only in a small number of cases on the session layer. This is because each session has a specific combination of a transaction settings for a particular application. With a second-level object, you can reuse at the inner level, we have seen this reuse in many projects, including in an engineering in the company (between different session beans) and multiple Project between engineering. We have seen that if you use this strategy, your design can often use the state of SESSION beans as a Facade object. Because of a user, each stateless session bean is not unique, which allows you to get additional scalability provided by stateless beans. Since we already know the type of FACDE, we can start to see which types of facade can provide. We see that the facade method is usually the following types:

The Collector method usually begins with "GET", returns an object or an object collection (which is emulation in EJB 1.0, a Java Collection in EJB 1.1 and 2.0). As described in [Brown 2000], the Collector method is implemented in the Factory object. The UPDater method is positioned and updated an Entity Bean or an Entity Bean set based on the information that is the value of the value of the parameter. The method name is often starting with "Update" or "SET". The implementation of the Updater method can be placed in the Factory like [Brown 2000], or in a separate class. Action method (such as the implementation of Transfer (String FromCtNum, String toAcctNum, BigDecimal Amount) is placed in the Action object. Session Facade Creation Rule Since you see the SESSION FACADE interface, what is the object behind the session facade, then the next question is "How many session facade should I have?" You should not have too many Session Facade, Otherwise, it will lose the benefits of the FACADE mode. However, if the entire application corresponds to a session facade which may become a "huge object" 5 and some problems in itself. Here is some rules for designing Session Facade so you can use it properly (more or too little).

Find a function subsystem from your application. For example, a subsystem named order management, billing management, and transport management is three Facade objects that may have in an application. Back to your Use-case and related use case groups. A set of related use cases (such as purchasing stocks, sale stocks and access) can form an internal organism system, such as "stock trading". This inner galaxy system may share a lot of inner objects and is the best candidate using Session Facade. [SUN 2001] This problem is discussed further. Don't make all a single usage in Session Facade. This will cause the system distribution cross section too much. In this case, the client will have to manage a very much EJB reference and HOME. After completing the initial work, look at the relationship between the second layer object in your design. If you see a value-value object, Factory and Action's non-intersecting group, then divide FACADE into two or more Facade according to the actual grouping method. Another session mode Since you have convinced that the data source should be used to pack the data source, you should also strictly lay out in these FACADE implementations, you may want to know the user-specific application status (if there What will be saved where it is saved. Based on my claim to design the Session Facade to handle multi-use case requests, you may also want to know where the use is actually implemented. To understand how to apply it, we use the following definition from [Jacobson 199]]: "Control class represents coordination, sequential transactions, and control of other objects, often used to control related to specific examples." This solution The goal is to implement a "use case controller" object corresponding to a single use case one by one. Each use case controller will maintain some user-specific status, and however, one user is located in this case (for example, how much it has been implemented), and is also input to the user, The following steps must be performed next. In this way, we found a solution that can implement and write cases in a way that really does not rely on GUI. Then, implement these use case controller objects, what choices do you have? Because they must be stateful, we have two J2EE architecture to choose from:

A option is to turn the use case controller to a sequentially-sequential object, and then store and retrieve them in the httpsession. Of course, this can only be used in applications using the Servlet API. However, it can be applied to many applications, even those applications that use Applets and Application client GUI, because even in these cases, communication with server-side objects even by HTTP (also use SOAP) is also commonly used. Design Strategy. With httpsession as storage mechanisms make programmers easier because of the persistent and failover details of sessions in most application servers (such as WebSphere). However, in WebSphere, an HTTPSESSION is reasonably persistent, and its size will be limited (see [Gunther]), so this choice is only relatively small to use case controller objects. Another option is to use the status of the SESSION bean as a action example controller. Available Session Bean is a good solution that makes programmers don't have to worry about how to maintain session information. In the stateful session bean, this solution can even handle failover in the application server where the SESSION bean is automatically stored in a shared persistent memory. However, in the application server like WebSphere, the session bean is not stored in a shared persistent memory, and if the server crashes, this solution will cause the user session to fail. Moreover, in this way, the SESSION bean that uses a state will return to the old problem of increasing the total distribution cross section. Despite this, due to the stateful session bean acts as a FACADE, each client only needs to know a few use case controllers, which is reduced to this problem. Wrap around the circle, this mode brought us back to the FACADE mode we originally discussed. This mode is a layered manner that we can focus on handling your work while allowing us to reuse something to constitute our solution. We don't have to design the entire system one time, but you can repeatedly use these modes, then look at a reusable object as a result. Summary I briefly analyze some rules for building session facade this article. You have seen how to organize the object called by Session Facade, how to set up Session Facade. You also saw some methods of designing the use case controller with Session Facade. I hope that the application of these rules can improve your EJB design adaptability and performance. Acknowledgments to thank Martin Fowler to review the draft of this article and put forward profound comments. At the same time, I would like to thank Craig Larman's profound insight. He made me understand that SESSION FACADE has two complementary modes. bibliography

Erich Gamma, Richard Helms, Ralph Johnson with John Vlissides Complete Design Patterns: Elements of Reusable Object-Oriented Design, Addison-Wesley, 1995. [Gamma] Martin Fowler's Analysis Patterns: Reusable Object Oriented Model, Addison-Wesley, 1997. [Fowler] Martin Fowler's Information Systems Architectur. [Fowler 2001] Sherman Alpert, Kyle Brown, with Bobby Woolf, the Design Patterns SmallTalk Companio, Addison-Wesley, 1996. [Alpert] William Brown, Ralph Malveau, Hays McCormick with Thomas Mobray, Antipatterns: Refactoring Software, Architectures, And Projects in Crisis, John Wiley and Sons, 1998. [Brown 1998] Kyle Brown, Philip Eskelin and Nat Pryce, "A Small Pattern Language for Distributed Component Design", is submitted to Monticello, 1999 in the Pattern Language Of Programs, PLOP. The paper is published in the Ratio Group Web Site. [Brown 1999] Kyle Brown's "Layered Architectures for EJB System", VisualAGe Domain. [Brown 2000] Kyle Brown's "Choosing The Right EJB TYPE: Some Design Criteria", VisualAGe Domain. [Brown 2000A] Kyle Brown with et. Al .Colled Enterprise Java Programming for IBM WebSphere, ADDISON-WESLEY Longman, Boston, May 2001. [Brown 2001] "Session Facade", Sun Java core J2EE mode, Java developer connection. [Sun 2001] Harvey Gunther's "WebSphere Application Server Developments Best Practices for Performance and Scalability". [Gunther] "Session Enity", Sun J2EE Planning blueprint. [Sun 2000] Sun Microsystems, "EJB 2.0 Specification", draft draft. [EJB 2.0] Richard Monson-Haefel, ENTERPRISE JAVABEANS, Second Edition, O'Reilly, 2000.

[Monson-Haefel] Ivar Jacobson with Et.Al, "The Unified Software Development Process", Addison-Wesley, 1999. [Jacobson 1999] Footnotes 1 Erich Gamma, Richard Helms, Ralph Johnson and John Vlissides Complete Design Patterns: Elements of Reusable Object-Oriented Design, Addison-Wesley, 1995, page 185. 2 Erich Gamma, Richard Helms, Ralph Johnson with John Vlissides Complete Design Patterns: Elements of Reusable Object-Oriented Design, Addison-Wesley, 1995, page 186. 3rich Gamma, Richard Helms, Ralph Johnson with John Vlissides Complete Design Patterns: Elements of Reusable Object-Oriented Design, Addison-Wesley, 1995, p. 187. 4ERICH GAMMA, RICHARD HELMS, RALPH JOHNSON with JOHN VLISSIDES: Elements of Reusable Object-Oriented Design, Addison-Wesley, 1995, page 193. 5william Brown, Ralph Malveau, Hays McCormick with Thomas Mobray, Antipals: Refactoring Software, Architectures, And Projects in Crisis, John Wiley and Sons, 1998, page 73. About the author Kyle Brown is an advanced Java consultant for IBM WebSphere Service. The role in WebSphere Service is to provide consulting services, education, and guidance to the "Top 500" customers on the "Fortune 500" customers on the WebSphere Service and Java 2 Enterprise (J2EE) technology. He is the Design Patternal Smalltalk Companion (design Mode Smalltalk partner), is also a famous contributor, or a spokesperson of the consequences of Enterprise Java, OO design and design pattern. Can contact Kyle via brownkyl@us.ibm.com.

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

New Post(0)