design patterns - a

Document Sample
design patterns - a Powered By Docstoc
					   SHEFFIELD HALLAM UNIVERSITY
Faculty of Arts, Computing, Engineering and Sciences




             DESIGN PATTERNS




                            By




S R Kumar        Archana Munnangi               Utkarsh Batwal
(17040037)              (17040771)                (17040842)




              Module: Object Oriented Methods
                                    DESIGN PATTERNS
INTRODUCTION –
        There are various recurring problems in software programming where it will be very
unlikely to try to invent a new solution to the recurring problems. Instead, it will be better to
reuse the solution that has been faced in past by someone to the same problems. Design pattern
is a general reusable solution to a commonly occurring problem in software programming or
software design. Design patterns are not finished designs that can be transformed directly into
code to solve a recurring problem but they provide us with the description of the general
solutions to design problems.
        Design patterns describe the relations and interactions of different class or objects or
types. They do not specify the final class or types that will be used in any software code, but give
an abstract view of the solution. Patterns show us how to build systems with good object oriented
design qualities by reusing successful designs and architectures. Expressing proven techniques
speed up the development process and make the design patterns, more accessible to developers
of new system.
        Good object oriented software design requires considering issues that may not become
visible until later in the implementation. Reusing design patterns helps to prevent subtle issues
that can cause major problems, and it also improves code readability for coders and architects
who are familiar with the patterns and we can also avoid alternatives that compromise
reusability.
Design patterns generally have four essential elements –


       Pattern Name – A descriptive and unique pattern name helps us in identifying and
        referring to the pattern.
       Problem – It explains the problem and its context (Context means a situation in which
        problem can arise).
       Solution – It describes the general arrangement of classes and objects that are used in the
        pattern to solve the problem.
       Consequences –A description of the results and trade offs caused by using the pattern.
       The Design patterns became popular when Erich Gamma, Richard Helm, Ralph Johnson,
and John Vlissides published their documentation. They introduced 23 patterns which were
grouped in three categories, namely – Creational, Structural and Behavioral Patterns. These
patterns are also called as GOF patterns (Gang-Of-Four). Their names are listed in the table
given below.




Purpose – Reflects what a pattern does
Scope – Specifies whether the pattern applies primarily to the Classes or to the Object. Class
patterns deals with the relationship between the classes and their subclasses whereas the Object
patterns deal with Object relationship that can be changed at runtime dynamically.


Creational Pattern –
       Creational design patterns abstract the instantiation process i.e. they deal with object
creation mechanisms, trying to create objects in a manner suitable to the situation. They make
the system independent of how its objects are created, interconnected and represented. The class
creational pattern use inheritance to vary the class that is instantiated, whereas an object
creational pattern will delegate instantiation to another object.
Creational design patterns controls the object creation and thus avoids the design problems that
occur while object creation.
Creational Design Patterns –
      Abstract factory: Provide an interface for creating families of related or dependent
       objects without specifying their concrete classes.
      Factory method: Define an interface for creating an object, but let subclasses decide
       which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
      Builder pattern: Separate the construction of a complex object from its representation so
       that the same construction process can create different representations
      Prototype pattern: They allow us to create instances by copying existing instances.
      Singleton pattern: Ensure a class only has one object, and provide a global point of
       access to it.

Among these we will see one example of Creational Pattern in detail.

Prototype Pattern –

Specify the kinds of objects to create new objects by copying the existing prototype object. We
can use a clone() method when we need a deep copy. In some cases copying an existing object
can be more efficient than creating a new object. Thus a prototype can be used at that instance.

Structure of Prototype Pattern –
Lets take an example of an animal cell to understand clone() method. The process of cell division
in animals is called mitosis in which a cell duplicates the chromosomes in its cell nucleus, in
order to generate two identical genotypes. Prototype pattern in that the original cell takes an
active role in creating a new instance of it.
                                                           Source code for cloning an
                                                           AnimalCell –
                                                           public class CellDivision {
                                                           public static void main(String[] args)
                                                           {
                                                           AnimalCell cell = new AnimalCell();
                                                           // create a clone

                                                           AnimalCell newAnimalCell =
                                                           (AnimalCell)cell.split();

                                                           }

                                                           }// End of class




Uses of Prototype –
      It hides the complexities of making new instance from the client.
      We can use prototypes to create new objects of various types in a complex hierarchy.
      It provides the options for the client to generate objects whose type is not known.
      In some cases copying an existing object can be more efficient than creating a new
       object.
      We use a prototype pattern when a system should be independent of how its objects are
       created, interconnected and represented.
Consequences –
           a) In this prototype we can add and remove products at runtime.
           b) We define a new behavior by specifying values for an object’s variable and not by
                 defining new classes.
           c) Reduced subclassing by cloning a prototype.
Disadvantages –
The main drawback of using the prototype is that making a copy of the objects is sometimes very
complicated.
Structural Pattern –
       Structural patterns deal with the composition of entities, i.e. classes and objects. They are
designed for realizing the relationships between the entities in a simple manner. It deals with
how classes and objects are composed to form large structures. For creating interfaces or
implementations, structural class design patterns uses a technique called inheritance. On the
other hand, the structural object design patterns describe ways to compose objects to add new
functionality.
Structural Design Patterns –
      Adapter Pattern: It will transform one interface of a class to the other interfaces.
      Bridge pattern: This pattern will divide the abstraction from the implementation so as to
       vary them in not dependent manner (i.e. independently).
      Composite Pattern: The same interface in every object is seen and the pattern will
       compose objects in a tree structures.
      Decorator Pattern: For getting an object dynamically, some additional responsibilities
       are attached. This Pattern for extending functionality it will provides an easy alternative
       to sub classing.
      Façade Pattern: For using the subsystem easier, facade defines a higher level interface.
      Flyweight Pattern: For performing the fine grained objects efficiently, it uses a sharing
       to save space.
      Proxy Pattern: provide a functioning of a class as an interface for another object.
Among these we will see one example of Decorator Pattern in detail.

Decorator Pattern –
       Decorator pattern will attach more responsibilities to an object dynamically. For
extending functionality it provides an easy alternative to subclassing. In this pattern without
creating a new derived class we can modify the behaviour of individual objects.
“Decorator Pattern is also called as wrapper.” In some cases, we have to modify and add
some extra responsibilities to an individual objects, but not to the whole class, in this situation
decorator patterns are implemented.
Structure of Decorator Pattern




       Let us apply this decorator pattern structure to a coffee Drinks problem. Here, Drinks is
Component    and    Coffea   Arabia,    JavaBlend,   Peaberry    and    Italian   Espresso   are
ConcreteComponent. The Decorator we have used is FlavoringDecorator, and the
ConcreteDecorator are SteamedMilk, WhippedCream, Vanillascoup and Mocha.




Sample Code for above design –

Implementation of base class Drinks

public abstract class Drinks {
String description = “Unknown Drinks”;
public String getDescription()
{
return description;
}
public abstract double cost();
}

Implementation of base class FlavoringDecorator

public abstract class FlavoringDecorator extends Drinks
{
public abstract String getDescription();
}

Implementation of CoreComponent

There are four core components as shown in the Drinks Decorator Pattern structure,

public class CoffeaArabia extends Drinks {
public CoffeaArabia() {
description = “Coffee Arabia”;
}
public double cost() {
return 59;
}
}

Implementation of Cost

       The above code returns the cost of Coffea Arabia which
is equal to 59 Rupees. Similarly we can make code for
JavaBlend, Peaberry and Italian Espresso. Now when we want
these Drinks with various Flavoring Decorators, the cost of
Flavoring decorators get added by the following code, for
example we add chocolate Mocha to our coffee drink, then

public class Mocha extends FlavoringDecorator {
Drinks drinks;
public Mocha(Drinks drinks)
{
this.drinks = drinks;
}
public String getDescription() {
return drinks.getDescription() + “, Mocha”;
}
public double cost() {
return 39 + drinks.cost();
}
}

Thus if the drinks ordered is Peaberry (79) and FlavoringDecorator is Mocha (39) we will get the
total cost to be 118 (79 + 39) Rupees.
Uses of a Decorator –
Decorator is used –
      For adding responsibilities to the individual objects dynamically and transparently
       without affecting other objects.
      For responsibilities that can be withdrawn.
      When extension by subclassing is impractical that means sometimes a large number of
       extensions are possible which would result in an explosion of subclasses. In such case
       Decorator pattern supports every combination.
Consequences –
   a) Provides more flexibility than static inheritance
   b) Offers a “pay as you go” approach to add responsibilities.
   c) Decorators and its component are not identical
   d) Lots of little objects are created.
Disadvantages –
Decorators can result in lots of little objects in our design and so its overuse can be complex.


Behavioral Patterns –
       Behavioral patterns deals with the algorithms and the assignment of responsibilities
between the objects. It not only describes the pattern of objects or classes but also the
communication pattern between them. Behavioral class patterns use inheritance to describe
algorithms and flow of control between classes. Thus they shift our focus from flow of control to
just concentrate on the object interconnection. Behavioral object pattern use the composition of
objects to perform some task that no single object can perform alone.
Behavioral Design Patterns –

      Chain of responsibility pattern: Avoids the coupling between sender and a receiver by
       passing the request through the chain of receiving objects until any object handles it.
      Command pattern: Request is encapsulated as an object, thereby allowing us to
       parameterize clients with different requests, queue or log requests, and support undoable
       operations.
      Interpreter pattern: Implement a specialized computer language to rapidly solve a
       specific set of problems by defining a representation for its grammar.
      Iterator pattern: Iterators are used to access the elements of an aggregate object
       sequentially without exposing its underlying representation
      Mediator pattern: Provides a unified interface to a set of interfaces in a subsystem and
       promotes loose coupling by keeping objects from referring to each other explicitly.
      Memento pattern: Provides the ability to rollback an object to its previous state.
      Observer pattern: It shows a one-to-many dependency between objects i.e. whenever
       any of the object changes its state all the dependants are notified to update automatically.
      State pattern: A clean way for an object to partially change its type at runtime
      Strategy pattern: Defines a family of algorithms and encapsulates each of them, such
       that they are interchangeable. Strategy lets the algorithm vary independently from clients
       using it.
      Template method pattern: Template Method lets subclasses redefine certain steps of an
       algorithm without changing the algorithm's structure.
      Visitor pattern: A way to separate an algorithm from an object.

Among these we will see one example of Strategy Pattern.

Strategy Pattern –
       The Strategy pattern is often used as an alternative to inheritance, where we can end up
spreading out the way we handle specific task over many class files. The strategy patterns says
that we should extract the volatile parts of the program code and encapsulate them in form of
objects, so that we can use these objects when we need them.
Uses of a Strategy Pattern –
Strategy is used:
      When we have a code which keeps on changing. This volatile code is generally separated
       out our main application for the ease of maintenance.
      When we want to change the algorithm that we use at runtime.
      When many related classes differ only in their behavior. Strategy can be used to
       configure a class with one of many behaviors.
    Structure of Strategy Pattern




    Let us apply this decorator pattern structure to a typical Game.




        The Character is an abstract class for all the other characters i.e. Max Payne, Mona,
Vinnie and Vladimir. Now here the weapon is the interface that all weapons implement. Here the
weapons are Ingram, Sniper, Kalashnikov and Grenade. All the actual characters and the
weapons form a concrete class. To switch the weapons each character will call the setWeapon()
method, which is defined in the Character superclass.
Calling the setWeapon()
public abstract class Character {
private WeaponBehaviour weapon;
private WalkBehaviour walk;
public void fight() {
weapon.useWeapon();       // delegation of fight behaviour
}
public void setWeapon(WeaponBehaviour w){
weapon = w;
}
...
abstract void display();
}

        During the fight the useWeapon() method is called on the current weapon set for a given
character to inflict great bodily damage on another character.
        Behaviors of the Character live in separate classes that implement a particular behavior
interface. That way, the Character classes does not need to know any of the implementation
details for their own behaviors. In addition, we no more rely on an implementation but on an
interface. Other types of objects can use these behaviors, too, because they’re not hidden inside
our Character class. We can also add new behaviors without modifying any of the existing ones
or touching our Character classes.


Sample Code for getting new weapon by a character–
public class Mona extends Character
{
public Mona()
{
weapon = new Sniper(); // The character Mona gets the Sniper weapon
…
}
public void display() {
...
}
}

Consequences –
    a) The algorithms may be related in an inheritance hierarchy and form Families of
        algorithms.
    b) Provides alternative to subclassing for the extendibility.
    c) Strategies eliminate conditional statements by encapsulating various behavior
        requirements in the separate strategy classes.
    d) They provide choice of different implementations for the same behavior.


Disadvantages –
       Strategy pattern can only be used when the variation in behavior is relevant to clients.
The client must understand how the strategies differ before selection of the appropriate one.
CONCLUSION –

        In the above paper we mentioned all the GOF patterns and explained three patterns, each
with an example. The situation in which these design patterns are applied depends upon the
applicability of the pattern.
        Design methods describe the recurring problem in design, how to solve them and how to
evaluate design. Yet, the design patterns haven’t been able to capture the experience of expert
programmers. The main problem in developing reusable software is that it often has to be
reorganized or refactored. A refactoring is a correctness preserving transformation that improves
the quality of the software. Refactoring involves isolating the classes into special-purpose and
general-purpose components, moving operations up or down the class hierarchy and rationalizing
the interfacing of classes. The basic GOF design patterns capture many structures that result
from refactoring. Using these patterns early in life of designing prevents later refactorings.


REFERENCES –


    1. Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. “Elements of Reusable
        Object-Oriented Software”
    2. Eric Freeman and Elisabeth Freeman. “Head First Design Patterns”
    3. Steve Holzner. Design Patterns For Dummies.
    4. Wikipedia      The       Free   Encyclopedia,   “Design     pattern   (computer     science)”
        <http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29> accessed on
        20 March 2008.
    5. The Pragmatic Craftsman <http://pragmaticcraftsman.com/design_patterns/> accessed on
        28 March 2008.