Session Facade with EJB && .NET

zhaozj2021-02-11  183

Session Facade

Provides a Coarse Graped Facade ON Fine Graped Objects To Improve Efficiency over a network.

In an object-oriented model, you do best with small objects that have small methods. This gives you lots of opportunity for control and substitution of behavior, and to use good intention revealing naming to help an application be easier to understand. So if you have an address object you would store and retrieve each piece of information individually. you have separate fields for the city, state, and zip code. you have separate getting methods to get this data, and separate setting methods to update this information. This allows the class to control updates easily, deciding to do special validation on a zip or determining a city automatically if the address only has a zip code. Other behaviors, such as determining if two addresses are within a few miles of each other, are also done ON A Fine Graped Basis. This Allows Clients To Clearly Ask for Exactly The Information and Behavior Thei Want.

One of the consequences of this fine grained behavior is that there is usually a lot of interaction between objects, and that interaction usually requires lots of method invocations. Within a single address space, this is no great issue. Method calls are cheap these days, And Clever Compilers and VMS CAN Eliminate Even SMALL COST. IN The VERY FEW CASES WHERE ITOES MAKE A DIFCERENCE, IT'S A SMALL JOB TO OPTIMIZE.

But this happy state does not exist when you make calls between processes. Remote calls are much more expensive because there is a lot more to do. Data may have to be marshaled, security may need to be checked, packets may need to be routed through .. switches If the two processes are running on machines on opposite sides of the globe, the speed of light may be a factor The brutal truth is that any inter-process call is orders of magnitude more expensive than an in-process call - even if both processes are on the same machine. Such a performance effect can not be ignored, even for us believers in lazy optimization.As a result any object that's intended to be used as a remote object needs a coarse grained interface that minimizes the amount of calls . needed to get something done If you want to change the city, state, and zip of a remote address; you want to do this in one call Not just does this affect your method calls, it also affects your objects Rather than ask.. For An ORDER AND IT'S ORDER LINES INDIVIDUALLY, You NEED TO Access And Update The Order and ORDER LINES IN A SINGLE CALL. This Affects Your Entire Object Structure.

This coarse grained interfaces come with a price. You give up the clear intention and fine-grained control that you get with small objects and small methods. Programming becomes more difficult and your productivity slows.

You can not rely on clever middleware to solve your problem. I've seen many sellers of distributed objects say that you can just take a regular object model and add CORBA (for instance) to make the whole thing distributed in a simple step. They point out that with their powerful software you only pay the price of a remote call if the call is actually remote. So you can program fine grained objects and only pay a performance cost should you actually use them remotely.Frankly, that does not wash. The point is that if you use a fine grained object remotely, it's performance will suck. If you use coarse-grained objects inside a process you lose productivity. There's no point taking a fine grained object and making it remotable just in case you Want to Call IT Remotely. Either it's a remote object or it isn't. The Fundamental Issue is this You NEED To Have Fine Graped Objects Wtem, a process and coarse grained Objects Between Processes.

A Session Facade Is a Coarse-Graped Facade Over A Web of Fine-grained Objects. None of the Fine-Grained Objects Have A Remote Interface and The Session Facade Does Not Contain Any Domain Logic.

HOW it works

Session Facade tackles the distribution problem by the standard OO approach of separating distinct responsibilities into different objects, and as a result has become the standard pattern for this problem Firstly I recognize that fine-grained objects are the right answer for complex logic -. So I ensure that any complex logic is placed in fine-grained objects which are designed to collaborate within a single process. to allow them to be accessed efficiently remotely I make a separate facade object to act as a remote interface. The facade, as the name implies , is merely a thin skin that switches from a coarse grained to a fine grained interface.In a simple case, like an address object, a Session Facade would replace all the getting and setting methods of the regular address object with one getter and one setter : OFTEN Referred to As Bulk Accessors. When a Client Calls a Bulk Setting Method, The Address Facade Reads The Data from The Setting Method and Calls The Individual Accessors on T he real address object (see Figure 1). The facade does nothing more than this. This way all the logic of validation and computation stays on the address object where it can factored cleanly and be used by other fine-grained objects.

Figure 1: One Call to a famade causes several calls from the facade to the domain Object

In a more complex case a single Session Facade may act as a remote gateway for many fine-grained object. An order facade may be used to get and update information for an order, all its order lines, and maybe even some customer data as well .

In transferring information in bulk like this, you need to transfer this information in a form that can easily be moved over the wire. If your fine-grained classes are present on both sides of the connection, and these objects are serializable, then you can transfer the objects directly by making a copy. In this case a getAddressData method would create a copy of the original address object. The setAddressData would receive an address object and use this address to update the data of the actual address object. (This assumes that the original address object needs to preserve its identity and thus can not be just replaced with the new address.) Often, however you can not do this. you may not want to duplicate your domain classes on multiple processes. Often it's difficult to serialize a segment of a domain model due to its complicated relationship structure. The client may not want the whole model, just a simplified subset of it. In these cases it makes sense to use a Data Transfer Object as The Basis of The Transfer.

In the sketch, I've shown a Session Facade that corresponds to a single domain object. While this is not uncommon and is easy to understand, it is not the most usual case. A single Session Facadewould have a number of methods each designed to pass on information from several objects. So getAddressData and setAddressData would be methods defined on a class like CustomerService which would also have methods along the lines of getPurchasingHistory and updateCreditData.

The question of granularity is one of the most tricky questions that comes up with Session Facade. Some people like to make fairly small Session Facades, such as one per use case. I prefer a coarser grained structure with much fewer Session Facades. For even a moderate sized application I might have just a single Session Facade. Even for a large application I may only have half a dozen Session Facades. This means that each Session Facade has a lot of methods, but since these methods are small I do not see this as a problem.You design a Session Facade based on the needs of a particular client usage. The most common example would be the need to view and update information through a user interface. In this case you might have a single Session Facade for a family of screens with one bulk accessor method for loading and saving the data for each screen. Pressing buttons on a screen, to change a order's status, would invoke command methods on the facade. Quite often you'll have different metho ds on the Session Facade that do pretty much the same thing on the underlying objects. This is common and reasonable. The facade is designed to make life simpler for external users, not the internal system, so if the client process thinks of it as a Different Command, IT IS A DIFFERENT COMMAND - EVEN IT All Goes To The Same Internal Command.

Session Facade can be stateful or stateless. A stateless Session Facade can be pooled, and this can improve resource usage and improve performance, especially in a B2C situation. However if the interaction involves state across a session, then it needs to store session state somewhere using Client Session State or Database Session State or a some implementation of Memento Session State. A stateful Session Facade can hold onto its own state, which makes for an easy implementation of Memento Session State. This may lead to performance issues when you have thousands of simultaneous users.As well as providing a coarse-grained interface, several other responsibilities naturally go to the Session Facade. The methods of a Session Facade are a natural point to apply security. An access control list can say which users can invoke calls on which Methods of a sessions facade. The session facade method to apply transactional control. a session facade method can Start A TRA nsaction, do all the internal work and then commit the transaction at the end. Each call makes a good transaction since you do not want a transaction open when return goes back to the client, since transactions are not built to be efficient for such Long Running Cases.

When to use it

Use Session Facade whenever you need remote access to a fine-grained object model. By using Session Facade you gain the advantages of a coarse grained interface while still keeping the advantage of fine grained objects. This gives you the best of both worlds.

The most common case of using this is between a presentation and a Domain Model where they may run on different processes. You'll get this between a swing UI and server domain model, or with a servlet and a server object model if the application and web servers are different processes.If all your access is within a single process, then you do not need this kind of conversion. So I would not use this pattern to communicate between a client Domain Model and its presentation nor between a CGI script And Domain Model That Are Running All INE Web Server. You don't test to see session Facade Used with a Transaction Script, Since A Transaction Script is inherently a coarser grained structure.

Session Facade's imply a synchronous, that is a remote procedure call style of distribution. Often you can greatly improve the responsiveness of an application by going with an asynchronous, message based style of remote communication. Indeed there are many compelling advantages for an asynchronous approach. Sadly Discussion of Asynchronous Patterns is outside the scope of this book.

Further Reading

.

Example: USING A Java Session Bean Asia Sense Facade (Java)

If you are working with the Enterprise Java platform, then a good choice for a distributed facade is a session bean. Session beans are remote objects, they may be stateful or stateless. In this example I'll run a bunch of plain old Java objects inside an EJB container and access them remotely through a session bean that's designed as a Session Facade. Session bean's are not particularly complicated, so this example should make sense even if you have not done any work with them before.I feel the need for a couple of side notes here. Firstly I've been surprised by how many people seem to belive that you can not run plain objects inside an EJB container in Java. I hear the question "are the domain objects Entity Beans?". .............................

My Other Side Note Is NOT TO POINT OUT THIS NOT THE ONT OUT THIS NOT THE IT CAN BE Used to Host Transaction Scripts. I'll Look At That Usage Elsewhere, in this case I'm using it as a Session facade.

In this example I'll look at remote interfaces to accessing information about music albums. The Domain Model consists of fine grained objects that represent an artist, and album, and tracks. Surrounding this are several other packages that provide the data sources for the application Fighe.

Figure 2: Packages The Remote Interfaces

The dto package contains Data Transfer Objects that help us move data over the wire to the client. They have simple accessor behavior and also the ability to serialize themselves in binary or XML textual formats. In the remote package are assembler objects that will move data between the domain objects and the Data Transfer Objects. If you're interested in how this works see the discussion of Data Transfer Object.To explain the facade I'll assume I can move data back and forth into Data Transfer Objects and concentrate on the remote interfaces. A single logical Java session bean has three actual classes. Two of these make up the remote API (and in fact are Java interfaces) the other is the class that implements the API. The two interfaces are the AlbumService itself and the home object : AlbumHome. The home object is buy by the name service to get access to the district, hAd, That's a detail on ejb That I'll Skip over here. PortS in the session facade itself: Which is A .

Class AlbumService ...

String Play (String ID) throws RemoteException;

String getalbumxml (string id) throws remoteException;

Albumdto getalbum (string id) throws remoteexception;

Void Createalbum (String ID, String XML) THROWS RemoteException;

Void Createalbum (String ID, Albumdto DTO) Throws RemoteException;

Void Updatealbum (String ID, String XML) Throws RemoteException;

Void Updatealbum (String ID, Albumdto DTO) THROWS RemoteException;

Void addartistnamed (string id, string name) throws remoteException;

Void addartist (String ID, String XML) THROWS RemoteException;

Void addartist (string id, artistdto dto) throws RemoteException; Artistdto getArtist (String ID) throws RemoteException;

You'll notice that even in this short example, I see methods for a two different classes in the Domain Model:. Artist and album I also see minor variations on the same method Methods have variants that use either the Data Transfer Object or an. XML string to move data into the remote service. This allows the client to choose which form to use depending on the nature of the client and of the connection. As you can see, for even a small application this can lead to many methods on AlbumService .

Fortunately The Methods Themselves Are Very Simple. Here Are The Ones for Manipulating Albums.

Class AlbumServiceBean ...

Public albumdto getalbum (string id) throws remoteexception {

Try {

Return new albumassembler (). Writedto (Registry.getalbum (ID));

} catch (throwable e) {

Throw New ApplicationException (E);

}

}

Public string getalbumxml (string id) throws receexception {

Try {

Albumdto DTO = New AlbumasseMbler (). WriteDto (Registry.getalbum (ID));

Return DTO.TOXMLSTRING ();

} catch (throwable e) {

Throw New ApplicationException (E);

}

}

Public void createalbum (String ID, Albumdto DTO) throws remoteexception {

Try {

New albumassembler (). Createalbum (ID, DTO);

} catch (throwable e) {

Throw New ApplicationException (E);

}

}

Public void createalbum (string id, string xml) throws receexception {

Try {

Albumdto DTO = Albumdto.readxmlstring (XML);

New albumassembler (). Createalbum (ID, DTO);

} catch (throwable e) {

Throw New ApplicationException (E);

}

}

Public void updatealbum (string id, albumdto dto) throws remoteException {

Try {

New albumassembler (). Updatealbum (ID, DTO);

} catch (throwable e) {throw new applicationException (e);

}

}

Public void updatealbum (string id, string xml) throws receexception {

Try {

Albumdto DTO = Albumdto.readxmlstring (XML);

New albumassembler (). Updatealbum (ID, DTO);

} catch (throwable e) {

Throw New ApplicationException (E);

}

}

As you can see, each method really does nothing more than delegate to another object, so each method is only a line or two in length (ignoring the noise of the try / catch blocks). This small example illustrates pretty nicely what a distributed facade SHOULD LOOK LIKE: A Long List of Very Short Methods with Very Little Logic In Them. The facade dam - Which is as it would be.

We'll just finish with a few words on testing It's very useful to be able to do as much testing as possible in a single process In this case I can do this by writing tests for the session bean implementation directly:.. These can be Run without deploying to the ejb container.

Class Xmltester ...

Private albumdto kob;

Private albumdto newkob;

Private albumservicebean facade = new albumservicebean ();

Protected void setup () throws exception {

Facade.initializefort ();

Kob = facade.getalbum ("kob");

Writer buffer = new stringwriter ();

Kob.Toxmlstring (buffer);

NEWKOB = albumdto.readxmlstring (New StringReader (Buffer.toString ()));

}

Public void testArtist () {

Assertequals (kob.getartist (), newkob.getartist ());

}

................... ..

Example: Web Service (.NET)

I was talking over this book with Mike Hendrickson, my editor at Addison-Wesley. Ever alert to the latest buzzwords, he asked me if I'd got anything about web services in it. I'm actually loath to rush to every fashion in these books, after due to the languid pace of book publishing any latest fashion that I write about will seem quaint by the time you read it. But it's a good example of how core patterns so often keep their value even with the latest technological flip- flops.At it's heart a web service is nothing more than an interface for remote usage As such the basic advice of Session Facade still holds:. build your functionality in a fine-grained manner, and then layer a Session Facade over the fine-grained Model in Order to Handle Web Services.

For the example, I'll the same basic problem as I described above, concentrating just on the request for information about a single album Figure 3 shows the various classes that take part They fall into the familiar groups:.. Album Service is the Session Facade, Two Data Transfer Objects, Three Objects in A Domain Model and an assebers.

Figure 3: Classes for the Album Web Service

The Domain Model is absurdly simple, indeed for this kind of problem you'd be better off using a Table Data Gateway to create the Data Transfer Objects directly - but that would rather spoil the example of showing a Session Facade over a domain model.

Class Album ...

Public String Title;

Public Artist Artist;

Public ilist tracks {

Get {return arraylist.readonly (tracksdata);

}

Public void addtrack (track arg) {

TracksData.Add (arg);

}

Public void RemoveTrack (Track Arg) {

Tracksdata.remove (arg);

}

Private ilist tracksdata = new arraylist ();

Class Artist ...

Public String Name;

Class TRACK ...

Public String Title;

Public ilist performers {

Get {return arraylist.readonly (performersdata);

}

Public void addperformer (artist arg) {

PerformersData.Add (arg);

}

Public void RemovePerformer (Artist Arg) {

PerformersData.Remove (arg);

}

Private ilist performersdata = new arraylist ();

I Use Data Transfer Objects for Passing The Data Over The Wire. There Are Just Data Holders Which Flatten The Structure for The Purposes of The Web Service.

Class Albumdto ...

Public String Title;

PUBLIC STRING ARTIST;

Public trackdto [] tracks;

Class TRACKDTO ...

Public String Title;

PUBLIC STRING [] Performers;

Since this is .NET, I don't need to write any code to serialize and resto xml. The .net framework comes with the appropriate Serializer Class to do the job.

Since this is a Web Service, I Also Need To Declare The Structure of the Data Transfer Objects in Wsdl. The Visual Studio Tools Will Generate The WSDL for Me, And I'm a Lazy Kind of Guy, SO I'll Let IT DO That. Here's The Xml Schema Definition That Corresponds To The Data Transfer Objects.

Being XML, It's A Particularly Verbose Form of Data Structure Definition, but it does the job.

To get the data from the domain model to the data transfer object I need an assemer.

Class Albumassembler ...

Public Albumdto WriteDto (Album Subject) {

Albumdto result = new albumdto ();

Result.Artist.Name;

Result.title = SUBJECT.TITLE;

ArrayList Tracklist = New ArrayList ();

Foreach (TRACK TIN SUBJECT.TRACKS)

TrackList.Add (WriteTrack (T));

Result.tracks = (TRACKDTO []) TrackList.toArray (Typeof (TRACKDTO));

Return Result;

}

Public TRACKDTO WRITETRACK (TRACK SUBJECT) {

Trackdto results = new trackdto ();

Result.title = SUBJECT.TITLE;

Result.performers = new string [Subject.performers.count];

ArrayList Performerlist = new arraylist ();

Foreach (Artist a in subject.performers)

PerformerList.Add (a.name);

Result.performers = (String []) PerformerList.toArray (TypeOf (String));

Return Result;

}

The las...................

Class AlbumService ...

[WebMethod]

Public albumdto getalbum (string key) {

Album Result = new albumfinder () [key];

IF (Result == NULL) Throw New Soapexception ("Unable to find album with key:" key, soapexception.clientfaultcode;

Else Return New AlbumasseMbler (). WriteDto (Result);

}

Of Course, this isn't The Real Interface Definition - That comes from the WSDL File. Here Are The Relevant Bits

As expected, WSDL IS Rather More Garrulous Than Your Average Politician, But Unlike So Many of Them - It Does Get The Job Done. I Can Now Invoke The Service By Sending A Soap Message of To Form

>>

akeystring

The important thing to remember about this example is not the cool gyrations with SOAP and .NET, but the fundamental layering approach. Design an application without distribution, then layer the distribution ability on top of that with Session Facades and Data Transfer Objects.

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

New Post(0)