The Facade Pattern

The Facade Pattern

The best way to understand the facade pattern is to look at a component diagram of a system before and after using a facade.

Figure 4-12 shows the front end of a Web site communicating with an application on the Web server. In the right side of the diagram, the front end code is accessing various objects in the application. On the left, showing the facade, the front end communicates only with the facade object, which in turn delegates responsibilities to the internal objects.


Figure 4-12

Say that you designed a small Web application. Over time, your client kept adding new features to it, and gradually the number of classes in the application increased. Certain pages on your Web site started building up many calls to the various objects. Such pages might resemble the following example.

   $dbManager = new DBManager();    $userArray = $dbManager.getNewUsers();    $emailer = new Emailer();    $stats = new StatLog();    for ($i = 0; $i < count($userArray[$i]; $i++) {      $user = $userArray[$i];      $userPref = $user->getMailPreference();      $userMail = $user->getEmail();      if ($userPref == true) {             $emailer->sendMailToUser($userMail);      } else {             $stats->storeUnmailedUser($user->getID());      }    } 

The preceding hypothetical code would send an e-mail to new users who indicated they want to receive mail. If they don't want to receive mail, their userID would be sent to a part of the application that manages statistics about users. Although this code isn't too ugly, if you had to mix in large amounts of HTML and get information back to report to the user, it might become unwieldy. Another version of using the Facade pattern follows.

   Application::mailNewUsers(); 

Now, anytime this functionality is required, the front end just requests it from the facade, in this case the Application class. All messages from the front end of the site go through the Application class and never interact directly with the other objects in the system. The Application object's methods can be static because you don't even need an instance of the Application class.

Notice that the client of the Application class doesn't need to know how it works internally. One good result of this, in addition to cleaner code, is that it will allow a separation of front-end presentation and backend functionality. The less your application is tied up in a particular presentation of HTML, the more likely it is to be reusable elsewhere. There's more discussion of this good design practice in Chapter 13, "Model View Controller.''



Professional PHP5 (Programmer to Programmer Series)
Professional PHP5 (Programmer to Programmer Series)
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 182
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net