Wednesday, 9 November 2011

FACADE DESIGN PATTERN

Problem

A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem.

Discussion

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.

Structure

Facade takes a “riddle wrapped in an enigma shrouded in mystery”, and interjects a wrapper that tames the amorphous and inscrutable mass of software.
Facade scheme

Facade:-
The facade class abstracts Packages 1, 2, and 3 from the rest of the application.
Clients:-
The objects using the Facade Pattern to access resources from the Packages.

Example

The Facade defines a unified, higher level interface to a subsystem that makes it easier to use. Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.
Facade example 
 

Monday, 7 November 2011

Proxy Pattern

Problem 

You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client.

Discussion

Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object.
There are  common situations in which the Proxy pattern is applicable.
  1. A virtual proxy is a placeholder for “expensive to create” objects. The real object is only created when a client first requests/accesses the object.
  2. A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
  3. A smart proxy interposes additional actions when an object is accessed. Typical uses include:
    • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
    • Loading a persistent object into memory when it’s first referenced,
    • Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Structure

By defining a Subject interface, the presence of the Proxy object standing in place of the RealSubject is transparent to the client.
Proxy scheme

Example

The Proxy provides a surrogate or place holder to provide access to an object. A check or bank draft is a proxy for funds in an account. A check can be used in place of cash for making purchases and ultimately controls access to cash in the issuer’s account.
Proxy example

 

Facade Design pattern ( Structure)

Structure:

FACADE

Name : Facade Design Pattern(Structural pattern)

Intent : Provides a unified interface to a set of interfaces in a subsystem.

Facade defines a higher-level interface that makes the subsystem easier to use.

Wrap a complicated subsystem with a simpler interface.

Problem : A segment of the client community needs a simplified interface to the overall

functionality of a complex subsystem.

Discussion: 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 users may need...

The Facade objest should be fairly simple facilitator. it should not become an all-

knowing object...






factory method pattern









factory method pattern

factory method pattern

The factory method pattern is an object oriented design pattern to implement the concept of factories.Like other creational patterns ,it deals with the problem of creating objects without specifying the exact class of the object that will be created.




The creation of object is usually a complex process .The object creation may lead to significant duplication of code,may require information not accessible to the composing object ,may not provide sufficient level of abstraction or may otherwise not be a part of composing object.The factory method design patterns handles these problems by defining a seperate method for creating the object,which subclasses can then override to specify the derived type of product that will be created.




some of the processes required in creating of the object include




  • Determining which object to create


  • Managing the lifetime of the object


  • Managing specialized build up and tear down concerns of the objects


The term factory method refers to a method of a factory whose main purpose is creation of objects



Factory Method Pattern

Name : Factory Method Pattern

It's easy to think of factories in the real world - a factory is just somewhere that items gets produced such as cars, computers or TVs. In the same way, the Factory method is a pattern used to facilitate the creation of other objects. Factory method is also known as virtual constructor.

Context:

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  • Defining a “virtual” constructor.
  • Refers to the newly created object through the common interface.

Problem:

A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation.

Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create.

  • a class may want it's sub classes to specify the objects to be created.
  • a class may delegate responsibility to one of several helper sub classes so that knowledge can be localized to specific helper sub classes.

Solution:

Factory Method is a creational pattern. This pattern helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate. We call this a Factory Pattern since it is responsible for "Manufacturing" an Object. It helps instantiate the appropriate Subclass by creating the right Object from a group of related classes. The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.

  • Factories have a simple function: Churn out objects.
  • Obviously, a factory is not needed to make an object. A simple call to new will do it for you. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific sub classes which create them.

The Factory Pattern is all about "Define an interface for creating an object, but let the sub classes decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" . "The Factory Method lets a class defer instantiation to subclasses".

The roles of Factory Method pattern:

The Factory Pattern has a couple of roles - a Creator and aConcrete Creator. This pattern is used when a class (theCreator) does not know beforehand all the sub classes that it will create. Instead, each subclass (the Concrete Creator) is left with the responsibility of creating the actual object instances.

Iterator Design Pattern

Iterator Design Pattern:


Intent:


Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms.
Promote to “full object status” the traversal of a collection.
Polymorphic traversal


Problem:


Need to “abstract” the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently.


Discussion:


“An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you’ll require. You might also need to have more than one traversal pending on the same list.” And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable.
The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.
The Iterator abstraction is fundamental to an emerging technology called “generic programming”. This strategy seeks to explicitly separate the notion of “algorithm” from that of “data structure”. The motivation is to: promote component-based development, boost productivity, and reduce configuration management.
As an example, if you wanted to support four data structures (array, binary tree, linked list, and hash table) and three algorithms (sort, find, and merge), a traditional approach would require four times three permutations to develop and maintain. Whereas, a generic programming approach would only require four plus three configuration items.


Structure:


The Client uses the Collection class’ public interface directly. But access to the Collection’s elements is encapsulated behind the additional level of abstraction called Iterator. Each Collection derived class knows which Iterator derived class to create and return. After that, the Client relies on the interface defined in the Iterator base class.




Example:
The Iterator provides ways to access elements of an aggregate object sequentially without exposing the underlying structure of the object. Files are aggregate objects. In office settings where access to files is made through administrative or secretarial staff, the Iterator pattern is demonstrated with the secretary acting as the Iterator. Several television comedy skits have been developed around the premise of an executive trying to understand the secretary’s filing system. To the executive, the filing system is confusing and illogical, but the secretary is able to access files quickly and efficiently.
On early television sets, a dial was used to change channels. When channel surfing, the viewer was required to move the dial through each channel position, regardless of whether or not that channel had reception. On modern television sets, a next and previous button are used. When the viewer selects the “next” button, the next tuned channel will be displayed. Consider watching television in a hotel room in a strange city. When surfing through channels, the channel number is not important, but the programming is. If the programming on one channel is not of interest, the viewer can request the next channel, without knowing its number.

Sunday, 6 November 2011

Documentation- Iterator Deisgn Pattern

Iterator:
The Iterator pattern separates the details of traversing a collection so that they can vary independently. Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. An aggregate object is an object that contains other objects for the purpose of grouping those objects as a unit. It is also called a container or a collection.


Motivation:
An aggregate object such as a list:
It should allow a way to traverse its elements without exposing its internal structure.
It should allow different traversal methods.
It should allow multiple traversals to be in progress concurrently.


Structure:


















Participants

Iterator:
Defines an interface for accessing and traversing elements.
ConcreteIterator:
Implements the Iterator interface.
Keeps track of the current position in the traversal of the aggregate.
Aggregate:
Defines an interface for creating an Iterator object.
ConcreteAggregate:
Implements the Iterator creation interface to return an instance of the proper ConcreteIterator.


Implementation Issues:

1. Who controls the iteration?: A fundamental issue is deciding which party controls the iteration,the iterator or the client that uses the iterator. When the client controls the iteration, the iterator is called an external iterator, and when the iterator controls it, the iterator is an internal iterator.
The client => more flexible; called an external iterator
The iterator itself => called an internal iterator

2. Who defines the traversal algorithm?: The iterator is not the only place where the traversal algorithm can be defined. The aggregate might define the traversal algorithm and use the iterator to store just the state of the iteration. We call this kind of iterator a cursor, since it merely points to the current position in the aggregate.
The iterator => more common; easier to have variant traversal techniques
The aggregate => iterator only keeps state of the iteration.

3. How robust is the iterator?: It can be dangerous to modify an aggregate while you're traversing it. If elements are added or deleted from the aggregate, you might end up accessing an element twice or missing it completely.
An iterator that allows insertion and deletions without affecting the traversal and without making a copy of the aggregate is called a Robust Iterator.

4. Additional Iterator operations: The minimal interface to Iterator consists of the operations First,Next, IsDone, and CurrentItem. Some additional operations might prove useful.

5. Using polymorphic iterators in C++: Polymorphic iterators have their cost. They require the iterator object to be allocated dynamically by a factory method. Hence they should be used only when there's a need for polymorphism. Otherwise use concrete iterators, which can be allocated on the stack.

6. Iterators may have privileged access: An iterator can be viewed as an extension of the aggregate that created it. The iterator and the aggregate are tightly coupled. We can express this close relationship in C++ by making the iterator a friend of its aggregate.

7. Iterators for composites:External iterators can be difficult to implement over recursive aggregate structures like those in the Composite pattern, because a position in the structure may span many levels of nested aggregates. Therefore an external iterator has to store a path through the Composite to keep track of the current object.

8. Null iterators: A Null Iterator is a degenerate iterator that's helpful for handling boundary conditions. By definition, a NullIterator is always done with traversal; that is, its IsDone operation always evaluates to true.
Null Iterator can make traversing tree-structured aggregates easier. At each point in the traversal, we ask the current element for an iterator for its children. Aggregate elements return a
concrete iterator as usual. But leaf elements return an instance of Null Iterator.

Applicability:

Use the Iterator pattern
· to access an aggregate object's contents without exposing its internal representation.
· to support multiple traversals of aggregate objects.
· to provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).

Consequences:

The Iterator pattern has three important consequences:
1. It supports variations in the traversal of an aggregate. Complex aggregates may be traversed in many ways.
For example, code generation and semantic checking involve traversing parse trees. Code generation may traverse the parse tree in-order or pre-order. Iterators make it easy to change the traversal algorithm: Just replace the iterator instance with a different one. You can also define Iterator subclasses to support new traversals.

2. Iterators simplify the Aggregate interface. Iterator's traversal interface obviates the need for a similar interface in Aggregate, thereby simplifying the aggregate's interface.

3. More than one traversal can be pending on an aggregate.An iterator keeps
track of its own traversal state. Therefore you can have more than one
traversal in progress at once.

Known Uses:

1. ObjectSpace's Java Generic Library containers
2. Rogue Wave's Tools.h++ collections
3. java.util.Enumeration interface
4. Java 2 Collections Framework Iterator interface

Related Patterns

1.Factory Method
Polymorphic iterators use factory methods to instantiate the appropriate iterator subclass.
2.Composite
Iterators are often used to recursively traverse composite structures.

The Iterator Pattern

Intent:

Provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.

The simplest iterator has a "next element" method, which returns elements in some sequential order until there are no more. More sophisticated iterators might allow several directions and types of movement through a complex structure.

Typically an iterator has three tasks that might or might not be implemented in separate methods:
  • Testing whether elements are available
  • Advancing to the next n.th position
  • Accessing the value at the current position

Bidirectional iterators might have additional methods for checking and advancing the reverse direction.

Example

In the demonstration application, AppletPainter class uses Java ArrayList Iterator facility to iterate the Command objects in the CommandContainer class.

Class Diagram

Singleton Pattern

Singleton Pattern

The singleton pattern is one of the simplest design patterns. It involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance, in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Context:
It's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and should provide a global point of access to objects.

Problem:
Singletons are very similar to Global Variables. Singleton Pattern has to do with how to limit instances. singletons have problems similar to globals; e.g., creating dependencies in vastly separated parts of the system, so side effects can appear far afield from their causes.

example problem statement by Daneil Earwicker: Imagine if a class A was using class D, which is a database access library. So within the implementation of A, it keeps declaring instances of D and using them to query a database. To make a Unit test for A, you have to declare a stub version of D that returns typical dummy values.
The singletons you describe above are no different from class D, really. I don't think you can get away from that. The dependencies of a class are not always made obvious in its interface. Personally, I think other the problems you mention are more annoying, and I would be itching to sort them out - otherwise there's a danger that your tests will be as confused as the classes.

Solution:
A better solution is to make the class itself responsible for keeping track of its instance. The class can ensure that no other instances can be created to create new objects and it can provide a way to access the instance.

Example - Configuration Classes
The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Abstract Factory Design Pattern

Name: ABSTRACT FACTORY DESIGN PATTERN

Context:
1. Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
2.Similar to Factory Method, but in AF the task of object creation is delegated to a different object, rather than just to a subclass.
3.The delegated object (the Abstract Factory) may itself make use of the Factory Method pattern.

Problem: Modularization is a big issue in today's programming. Programmers all over the world are trying to avoid the idea of adding code to existing classes in order to make them support encapsulating more general information. Take the case of a information manager which manages phone number. Phone numbers have a particular rule on which they get generated depending on areas and countries. If at some point the application should be changed in order to support adding numbers form a new country, the code of the application would have to be changed and it would become more and more complicated.

Solution: In order to prevent it, the Abstract Factory design pattern is used. Using this pattern a framework is defined, which produces objects that follow a general pattern and at runtime this factory is paired with any concrete factory to produce objects that follow the pattern of a certain country. In other words, the Abstract Factory is a super-factory which creates other factories (Factory of factories).
Provide a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes.
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.

STRUCTURE

The base component of the pattern are the abstract factory and the abstract products denoted by A and B in this case. To use the pattern a designer creates a concrete factory as a subclass of the abstract factory. In the fig two such classes have been designed concreteFactory1 and concreteFactory2. To accompany the new factory type, a concrete class is required for each product in the product suite. ConcreteFactory1 would thus be designed in tandem with product types Product A1,ProductB1 and so on for the other products.The different factories share a common interface, that designated by the AbstractFactory base.In the implementation of the operations the concrete factories create and make available their particular product types.client code references these product in terms of abstract product types only.

Example:Suppose we plan to manage address and telephone information in our application (Example Personal Informational manager) system. We will initially produce classes to represent Address and Telephone number data. Code these classes so that they store the relavent information and enforce business rules about their format.Ex: In few indian cities all telephone numbers are limited to 7 digits.Shortly we get another requirement to manage this application for another city/country.So we modify our logic in the Address and PhoneNumber to satisfy rules for another city/country and all of a sudden after managing for many countries sees our classes get bloated with code and difficult to manage. With every country added, we need to modify and recompile the classes to manage contact information.
It's better to flexibly add these paired classes to the system; to take the general rules that apply to address and phone number data,and allow any number of possible foreign variations to be "loaded" into a system.
The abstract factory solves this problem.Using this pattern,you define an AddressFactory- a generic framework for producing objects that follow the general pattern for an Address and PhoneNumber.At runtime,this factory is paired with any number of concrete factories for different countries,and each country has its own version of Address and PhoneNumber classes.
Instead of going through nightmare of adding functional logic to the classes,extend the Address to USAddress and PhoneNumber to USPhoneNumber for country US.Instances of both classes are created by USAddressFactory.This gives greater freedom to extend your code without having to make major structural modifications in the rest of the system.

USES:In Swing, the look and feel is established by installing an Abstract Factory.
1. To set the look and feel to match that of the native platform:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
2. Java.awtToolkit is an Abstract Factory.


CONSEQUENCES:
Benefits• Isolates concrete classes
• Allows to change product family easily
• Promotes consistency among products
Drawback• Adding a new product requires extending the abstract interface which implies that all of its derived concrete classes also must change. The following changes needs to be taken care of:
o New abstract product class is added
o New product implementation is added
o Abstract factory interface is extended
o Derived concrete factories must implement the extensions
o Client has to be extended to use the new product

Exploring the Factory Design Pattern

Exploring the Factory Design Pattern

Name : Factory Design Pattern

Context:

The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created .The factory method design pattern handles the problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object. Outside the scope of design patterns, the term factory method can also refer to a method of a factory whose main purpose is creation of objects.

The Problem:

One of the goals of object-oriented design is to delegate responsibility among different objects. This kind of partitioning is good since it encourages Encapsulation and Delegation.

  • Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create.
  • A class may want it's subclasses to specify the objects to be created.
  • A class may delegate responsibility to one of several helper subclasses so that knowledge can be localized to specific helper subclasses.

The Solution:

Factory Method is a creational pattern. This pattern helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate. We call this a Factory Pattern since it is responsible for "Manufacturing" an Object. It helps instantiate the appropriate Subclass by creating the right Object from a group of related classes. The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.

Factories have a simple function: Churn out objects.

Obviously, a factory is not needed to make an object. A simple call to new will do it for us. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific subclasses which create them.


Structure:

The Factory Pattern is all about "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses" Thus, as defined by Gamma et al, "The Factory Method lets a class defer instantiation to subclasses".

Figure 1 below illustrates the roles of the Factory Pattern.

Figure 1: The roles of the Factory Pattern

As shown in the figure, the Factory Pattern has a couple of roles - a Creator and a Concrete Creator. This pattern is used when a class (the Creator) does not know beforehand all the subclasses that it will create. Instead, each subclass (the Concrete Creator) is left with the responsibility of creating the actual object instances.

Implementation:


The implementation is really simple

  • The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
  • The factory instantiates a new concrete product and then returns to the client the newly created product (casted to abstract product class).
  • The client uses the products as abstract products without being aware about their concrete implementation.
Consequences:
Advantages:

  • Eliminates the need to bind application-specific classes into your code
  • Provides hooks for sub classing. Creating objects inside a class with a factory method is always more flexible than creating an object directly. This method gives subclasses a hook for providing an extended version of an object
  • Connects parallel hierarchies. Factory method localizes knowledge of which classes belong together. Parallel class hierarchies result when a class delegates some of its responsibilities to a separate class.
Disadvantages :

  • Clients might have to subclass the Creator class just to create a particular Concrete object.




Also See:
Abstract Factory, Template, and Prototype Patterns.