清单 1. 隐藏已不使用的方法 public Person getDirector() { // We can't call getDirector() any more on the entity bean // Call the new method, through this manager List directors = getDirectors(); // Return the first one in the list return (Person)directors.item(0); }
清单 2. 用会话 bean 掩盖数据结构 public List getCrew(String movieName) throws NamingException, RemoteException { List crew = new LinkedList(); EJBHomeFactory f = EJBHomeFactory.getInstance(); MovieHome movieHome = (MovieHome)f.lookup("java:comp/env/ejb/Movie", MovieHome.class); Movie movie = movieHome.findByName(movieName); crew.add(movie.getDirectors()); crew.add(movie.getProdUCers()); crew.add(movie.getExecutiveProducers()); // and so on... return crew; } public List getCast(String movieName) throws NamingException, RemoteException { List cast = new LinkedList(); EJBHomeFactory f = EJBHomeFactory.getInstance(); MovieHome movieHome = (MovieHome)f.lookup("java:comp/env/ejb/Movie", MovieHome.class); Movie movie = movieHome.findByName(movieName); crew.add(movie.getActors()); crew.add(movie.getStandIns()); // and so on... return cast; }
通过分离不同的应用程序层,以及使用业务逻辑来处理数据操作,您既阻止了对实体 bean 直接而且可能不安全的访问,又为您的 Web 层创建了更有意义的方法集。本例中,会话虚包充当了实体 bean 的封装器以及真正的业务逻辑单元,从而将原始数据转变成有意义的信息。