CSC/ECE 517 Fall 2012/ch2b 2w42 aa
Introduction
Facade Pattern
Intent
- Provide a unified interface to a set of interfaces in a subsystem.
- Wrap a complicated subsystem with a simpler interface.
Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that “power users” may need. The Facade object should be a fairly simple advocate or facilitator. It should not become an all-knowing oracle or “god” object.
Adapter Pattern
Intent<ref>Sourcemaking - Adapter Design Pattern - http://sourcemaking.com/design_patterns/adapter</ref>
- Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
- Wrap an existing class with a new interface.
- Impedance match an old component to a new system.
Convert the interface of a class into another interface clients expect. Adapter lets classes worktogether that couldn't otherwise because of incompatible interfaces.
Abstract Factory Pattern
Intent
- Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- A hierarchy that encapsulates: many possible “platforms”, and the construction of a suite of “products”.
- The new operator considered harmful.
If an application is to be portable, it needs to encapsulate platform dependencies. These “platforms” might include: windowing system, operating system, database, etc. Too often, this encapsulatation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code.
Mediator Pattern
Intent
- Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
- Design an intermediary to decouple many peers.
- Promote the many-to-many relationships between interacting peers to “full object status”.
Facade Pattern
Non-Software examples<ref>ASPAlliance - Facade Design Pattern - http://aspalliance.com/970_Facade_Design_Pattern.2</ref>
In most of the Pizza centers, orders will be given through phone calls with the customer interacting with the Customer service representative. In this case, consumers do not have access to the Billing system, Kitchen and delivery department. The customer service representative acts as an interface and interacts with each of the departments involved in the transaction and ensures that Pizzas are delivered to the consumer. Customer Service representative corresponds to the facade. Individual departments involved in the transaction correspond to Sub-systems.
Software examples
Web Service Facade Solution Architecture provides an example for Facade design pattern. In this architectural solution, instead of rewriting legacy applications or customizing those with middleware to connect to other applications one by one, this solution helps create a "facade" for the legacy application. Other applications are easily "plugged into" this facade. By modeling a legacy application into its basic functions of create, read, update, and delete and then exposing these functions as Web methods, the Web service facade solution allows other applications to access legacy data by making use of common Web services through standardized protocols. In this way, Facade decouples layers so that they do not depend on each other which can make it easier to develop, to use and to promote code re-use.
C# Example
using System; using System.Collections.Generic;
namespace DesignPatterns.Facade { public class OrderFacade { //Places an Order and Returns an Order ID public int placeOrder(int CustomerID, List<BasketItem> Products) { Order anOrder = new Order(); OrderLine anOrderLine = new OrderLine(); Address DespatchAddress = Address.getCustomerDespatchAddress(CustomerID); int OrderId = anOrder.requestOrderID(); anOrder.createOrder(OrderId, DespatchAddress); anOrderLine.addOrderLinesToOrder(OrderId, Products); return OrderId; } }
//order class public class Order { public int requestOrderID() { //Creates and Returns a Unique Order ID }
public void createOrder(int OrderId, Address DespatchAddress) { } }
//OrderLine Class public class OrderLine { public void addOrderLinesToOrder(int OrderId, List<BasketItem> Products) { } }
//Public Customer public class Address { public static Address getCustomerDespatchAddress(int CustomerID) { return new Address(); } //Address properties }
public class BasketItem { //BasketItem Properties } }
Adapter Pattern and Facade Pattern
Adapter class is a wrapper which modifies an existing class. It provides an alternate view of that class. In cases where a third party component is readily available and provides functionality that needs to be used, but the interfaces exposed by the component does not have an exact match with the system that is being developed, adapter classes can be used. The mismatch can be diverse such as the way arguments are handled, some assumptions about the underlying implementations, physical dimensions, misalignment, timing or synchronization etc. It may be unfortunate assumptions or competing standards. It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall outlet – some kind of adapter or intermediary is necessary.
Adapter Pattern creates an intermediate class that maps the one component to other. The calls to methods on the Adapter object is redirected by the adapter into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation.
Adapter Pattern Example
interface Shape { void draw(...); } Class LegacyLine { void draw(..) { } } Class LegacyRectangle { void draw(..) { } } Class Line implements Shape { adapter = new LegacyLine(); void draw(...) {adapter.draw(...)} } Class Rectangle implements Shape { adapter = new LegacyRectangle(); void draw(...) {adapter.draw(...)} }
In the example provided for the Facade pattern, the method placeOrder() uses the methods exposed by many other classes such as Order, OrderLine, Address etc to provide a high level view for the callers. The callers need not worry about the complexities in handling the sub-system. The users of the Class OrderFacade just invoke the method placeOrder() with the necessary arguments and rest of the process is taken care by placeOrder(). As can be seen in this case, a new method (placeOrder) was defined which has the logic and the necessary steps to handle all the sub-systems to create an order, create an id for the order, create a dispatch address etc.
In the example provided for the Adapter pattern, no new methods are defined. The existing method draw of LegacyRectangle is wrapped in a adapter class Rectangle. The methods in adapter classes does the necessary manipulations to the arguments and then passes to the original classes.
On similar lines, in the Facade example, assume that the user of OrderFacade needs to obtain order id in a different representation. To handle such scenario, a new adapter class OrderFacadeAdapter is defined. It implements all the methods of the OrderFacade and in each method where order id is referenced, it makes necessary changes to convert order id from one form to other and invoke other methods of the subsystem.
Example
public Class OrderFacadeAdapter { public OrderId placeOrder(...) { //convert order id from int to type 'OrderId' and return } }
Differences and similarities
- In both the Facade and Adapter pattern we have pre-existing classes.
- In the Facade, however, we do not have an interface we must design to, as we do in the Adapter pattern.
- We are not interested in polymorphic behavior<ref>Scribd - Facade Design Pattern - http://www.scribd.com/doc/2283673/Design-patterns-the-facade-and-adapter-pattern</ref> in the Facade, while in the Adapter, We probably am.(There are times when we just need to design to a particular API and therefore must use an Adapter)
- In the case of the Facade pattern, the motivation is to simplify the interface. With the Adapter, while simpler is better,We are trying to design to an existing interface and cannot simplify things even if a simpler interface were otherwise possible.
Bottom line is a Facade simplifies an interface while an Adapter converts the interface into a pre-existing interface.
Abstract Factory Pattern and Facade Pattern
Abstract factory pattern<ref>Freeman,E., and Robson,E.,and Bates,B.,and Sierra,K. 2004. Head First Design Patterns</ref> provides a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The “factory” object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them.
This mechanism makes exchanging product families easy because the specific class of the factory object appears only once in the application - where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory. Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.
Abstract Factory Example
The AbstractFactory defines the interface that all of the concrete factories will need to implement in order to product Products. ConcreteFactoryA and ConcreteFactoryB have both implemented this interface here, creating two seperate families of product. Meanwhile, AbstractProductA and AbstractProductB are interfaces for the different types of product. Each factory will create one of each of these AbstractProducts.
The Client deals with AbstractFactory, AbstractProductA and AbstractProductB. It doesn't know anything about the implementations. The actual implementation of AbstractFactory that the Client uses is determined at runtime.
As you can see, one of the main benefits of this pattern is that the client is totally decoupled from the concrete products. Also, new product families can be easily added into the system, by just adding in a new type of ConcreteFactory that implements AbstractFactory, and creating the specific Product implementations.
Facade Pattern Example
Considering the example for the Facade pattern, Client requires access to Employee objects, but in order to get that, it first need to contact the Database and retrieve the Company objects. It then retrieves Division objects from them and finally gains access to Employee objects. So, we see that It uses four classes and has to deal with complex details of the sub system. With Facade, the Client is shielded from most of the classes. It uses the Database Facade to retrieve Employee objects directly.
Differences and similarities between Facade and Abstract Factory patterns
- Facade is a structural design pattern whereas Abstract Factory pattern is a creational design pattern<ref>Erich,G., and Richard,H.,and Ralph,J.,and John,M.V. 1997. Design Patterns: Elements of Reusable Object-Oriented Software</ref>.
- Both are similar in a way that both provide an interface. Abstract Factory , provides kind of a Facade for creating products that belongs to its own factories.
- With the Abstract Factory Pattern we just provide a common factory builder for many different builders for the same thing. This can be used whenever we need to provide an interface to a set of builders meant to be used with something in common (the product) without bothering on what are we going to build or which factory are we going to use. The Facade pattern instead is used to provide a simple interface to a lot of different operations that the client classes should not see.
Thus we see that both patterns achieve quite different goals. The facade pattern is used when you want to hide an implementation or it is about changing interface of some class or set of classes. On the other hand Abstarct factory pattern is used when you want to hide the details on constructing instances. Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Mediator Pattern and Facade Pattern
Mediator Pattern is used to avoid the direct dependencies between reusable pieces of software i.e if one of the components changes, then all components which are directly connected to it changes. One of the important example is the resources permission in unix. There are three categories of permissions - owner, group and others. Some users with similar characteristics are formed into a group. Each user on the system can be a member of one or more groups, and each group can have zero or more users assigned to it. If we were to model this in software, we could decide to have User objects coupled to Group objects, and Group objects coupled to User objects. Then when changes occur, both classes and all their instances would be affected. An alternate approach would be to introduce an additional level of indirection - take the mapping of users to groups and groups to users, and make it an abstraction unto itself. This offers several advantages: Users and Groups are decoupled from one another, many mappings can easily be maintained and manipulated simultaneously, and the mapping abstraction can be extended in the future by defining derived classes.
Partitioning a system into many objects generally enhances reusability, but proliferating interconnections between those objects tend to reduce it again. The mediator object: encapsulates all interconnections, acts as the hub of communication, is responsible for controlling and coordinating the interactions of its clients, and promotes loose coupling by keeping objects from referring to each other explicitly.
Facade Example
class Logger { private LoggerImpl internalLogger; private LoggerManager manager; public void initLogger( String loggerName ) { this.internalLogger = manager.getLogger( loggerName ); } public void debug( String message ) { this.internalLogger.debug( message ); } }
The functionality already exist. The facade only hides it. In this hypothetical case, the LoggerManager handles the creation of the correct logger, and the LoggerImpl is a package private object that has the "debug" method. This way the Facade is not adding functionality he is just delegating to some existing objects.
Mediator Example
public void initLogger( String loggerName ) { this.loggerName = loggerName; if ( loggerName == "someLogger" ) { out = new PrintStream( new File("app.log")); } else if ( loggerName == "serverLog" ) { client = new Socket("127.0.0.1", 1234 ); } else if( loggerName == "dblog") { dbConnection = Class.forName()... . } } public void debug( String message ) { if ( loggerName == "someLogger" ) { out.println( message ); } else if ( loggerName == "serverLog" ) { ObjectOutputStrewam oos = new ObjectOutputStrewam( client.getOutputStream()); oos.writeObject( message ); } else if( loggerName == "dblog") { Pstmt pstmt = dbConnection.prepareStatment( LOG_SQL ); pstmt.setParameter(1, message ); pstmt.executeUpdate(); dbConnection.commit(); } }
In this code, the mediator is the one that contains the business logic to create the appropriate "channel" to log and also to make the log into that channel. He is "creating" the functionality
Differences and Similarities =
Mediator is similar to Facade in that it abstracts functionality of existing classes. Mediator abstracts/centralizes arbitrary communication between colleague objects, it routinely “adds value”, and it is known/referenced by the colleague objects (i.e. it defines a multidirectional protocol). In contrast, Facade defines a simpler interface to a subsystem, it doesn’t add new functionality, and it is not known by the subsystem classes (i.e. it defines a unidirectional protocol where it makes requests of the subsystem classes but not vice versa). Facade is an structural pattern, that is it describes the composition of the objects, while the mediator is an behavioral, that is , it describes the way the objects interact.
References
<references/>
Additional Reading
- Facade Pattern in Java at java.dzone.com
- Facade Pattern at dofactory.com
- Abstract Factory Pattern at Wikipedia
- Facade Design Pattern at Wikipedia
- Facade with Factory pattern at dofactory.com
- difference between facade and abstract factory pattern at stackoverflow.com
- McDonald,J. 2008. Design Patterns