Prototype Pattern (sort of) using Comparable


EJB programming & troubleshooting: Prototype Pattern (sort of) using Comparable

  1. Prototype Pattern (sort of) using Comparable (1 messages)

    My understanding of the Protoype design pattern is that it is used when creating an instance of a class is very time-consuming or otherwise complex. Rather than creating more instances, you make copies of the original instance, modifying them as appropriate. I want to apply a similar idea to entity EJBs. Assume I call an EJBHome.findByXXX() method to return a Collection of remote stubs. For example, EmployeeHome.findByLastName("Smith") would return all employees (as represented by remote interfaces to entity beans) with last name "Smith." Now assume that the underlying database query sorts all Smiths by first name. Therefore the Collection returned by findByLastName() has all values sorted by first name. So far so good I hope.

    Now assume I want to sort the Collection by some other criterion like employee ID. I could write another findByLastName() method (like findByLastNameIDSorted("Smith")) whose underlying query does a sort of the Smiths by ID rather than first name. But that is potentially an expensive call, and I already have a Collection of all the Smiths. My desire then is to simply sort the Collection the same way I would in conventional Java--by having the objects in the Collection implement Comparable and then calling Collections.sort() on the Collection. I would think that if I I do the following this might work:

    1) have Employee (the remote interface) simply extend Comparable
    2) have EmployeeBean implement Comparable so that calls to the remote interfaces' compareTo() method summon the beans' compareTo method(). The findByLastName() method will return the Collection already sorted by first name thanks to the query, but sorting the resulting Collection with a properly written compareTo() method will sort the original Collection by employee ID.

    Of course, if more than 2 ways of sorting the Collection is desired, then a Comparator can be used rather than implementing Comparable.

    So this is my idea. Can someone tell me if this makes any sense or if I am out of my mind?

    Thanks so much for reading this disertation! I welcome any insight you might have.
  2. I don't see how this is particularly related to the prototype pattern.
    This post is cross-posted on the EJB Design forum under a different name ("Sorting Beans") and also in another forum.

    Please do not cross-post. It breaks up the discussion and makes it harder for other users to find answers to their questions by reading the forum.