factorymethodanditeratorpattern

download factorymethodanditeratorpattern

of 14

Transcript of factorymethodanditeratorpattern

  • 8/7/2019 factorymethodanditeratorpattern

    1/14

    1.1 Introduction

    What is a design pattern?

    In software engineering, a design pattern is a general reusable solution to a commonly

    occurring problem in software design. A design pattern is not a finished design that can be

    transformed directly into code. It is a description or template for how to solve a problem that can

    be used in many different situations.

    Christopher Alexander says, "Each pattern describes a problem which occurs over and over

    again in our environment, and then describes the core of the solution to that problem, in such a

    way that you can use this solution a million times over, without ever doing it the same way

    twice"

    A design pattern names, abstracts, and identifies the key aspects of a common design

    structure that make it useful for creating a reusable object-oriented design. The design pattern

    identifies the participating classes and instances, their roles and collaborations, and

    distribution of responsibilities. Each design pattern focuses on a particular object-oriented design

    problem or issue. It describes when it applies, whether it can be applied in view of other design

    constraints, and the consequences and trade-offs of its use. Although design patterns describe

    object-oriented designs, they are based on practical solutions that have been implemented in

    mainstream object-oriented programming languages like Smalltalk and C++ rather

    procedural languages (Pascal, C, Ada) or more dynamic object-oriented languages (CLOS,

    Dylan, Self).

    Object-oriented design patterns typically show relationships and interactions between

    classes orobjects, without specifying the final application classes or objects that are involved.

    Many patterns imply object-orientation or more generally mutable state, and so may not be as

    applicable in functional programming languages, in which data is immutable or treated as such.

    Design patterns reside in the domain of modules and interconnections. At a higher level

    there are architectural patterns that are larger in scope, usually describing an overall pattern

    followed by an entire system.

    Page 1 of14

    http://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Software_designhttp://en.wikipedia.org/wiki/Code_(computer_programming)http://en.wikipedia.org/wiki/Object-orientedhttp://en.wikipedia.org/wiki/Interactionhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)http://en.wikipedia.org/wiki/Software_engineeringhttp://en.wikipedia.org/wiki/Software_designhttp://en.wikipedia.org/wiki/Code_(computer_programming)http://en.wikipedia.org/wiki/Object-orientedhttp://en.wikipedia.org/wiki/Interactionhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)
  • 8/7/2019 factorymethodanditeratorpattern

    2/14

    1.2 TYPES OF DESING PATTERNS

    There are many types of design patterns including: structural design patterns, computational

    design patterns, algorithm strategy patterns, implementation strategy patterns and execution

    patterns. Structural patterns address concerns related to the high level structure of an application

    being developed. Computational patterns address concerns related to the identification of key

    computations. Algorithm strategy patterns address concerns related to high level strategies that

    describe how to exploit application characteristic on a computation platform. Implementation

    strategy patterns address concerns related to the realization of the source code to support

    (I) How the program itself is organized and

    (II) The common data structures specific to parallel programming.

    Execution patterns address concerns related to the support of the execution of an application,

    including the strategies in executing streams of tasks and building blocks to support the

    synchronization between tasks.

    1.3 USES OF DESIGN PATTERNS

    Design patterns can speed up the development process by providing tested, proven development

    paradigms. Effective 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 improves code readability for coders and architects familiar with the

    patterns.

    Often, people only understand how to apply certain software design techniques to certain

    problems. These techniques are difficult to apply to a broader range of problems. Design patterns

    provide general solutions, documented in a format that doesn't require specifics tied to a

    particular problem.

    In addition, patterns allow developers to communicate using well-known, well understood names

    for software interactions. Common design patterns can be improved over time, making them

    more robust than ad-hoc designs.

    Page 2 of14

  • 8/7/2019 factorymethodanditeratorpattern

    3/14

    2. FACTORY METHOD

    The essence of the Factory method Pattern is to "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.

    Like othercreational patterns, it deals with the problem of creating objects (products) without

    specifying the exact class of object that will be created. The creation of an object often requires

    complex processes not appropriate to include within a composing object. The object's creation

    may lead to a significant duplication of code, may require information not accessible to the

    composing object, may not provide a sufficient level of abstraction, or may otherwise not be part

    of the composing object's concerns. The factory method design pattern handles these 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.

    2.1 CONCEPT

    In object-orientedcomputer programming, a factory is an object for creating other objects. It is

    anabstraction of a constructor, and can be used to implement various allocation schemes. For

    example, using this definition,singletons implemented by thesingleton patternare formal

    factories. A factory object typically has amethod for every kind of object it is capable of

    creating. These methods optionally accept parameters defining how the object is created, and

    then return the created object.

    Factory objects are used in situations where getting hold of an object of a particular kind is a

    more complex process than simply creating a new object. The factory object might decide to

    create the object's class(if applicable) dynamically, return it from an object pool, do complex

    configuration on the object, or other things.

    These kinds of objects have proven useful and several design patterns have been developed to

    implement them in any given language. For example, several "GoF patterns", like the "Factory

    method pattern", the "Builder" or even the "Singleton" are implementations of this concept.

    The "Abstract factory pattern" instead is a method to build collections of factories.

    Page 3 of14

    http://en.wikipedia.org/wiki/Creational_patternhttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Concern_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Subclass_(computer_science)http://en.wikipedia.org/wiki/Derived_typehttp://en.wikipedia.org/wiki/Object-orientedhttp://en.wikipedia.org/wiki/Computer_programminghttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Abstraction_(computer_science)http://en.wikipedia.org/wiki/Abstraction_(computer_science)http://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Singleton_patternhttp://en.wikipedia.org/wiki/Singleton_patternhttp://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Parameterhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Object_poolhttp://en.wikipedia.org/wiki/Object_poolhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Design_Patterns_(book)http://en.wikipedia.org/wiki/Builder_patternhttp://en.wikipedia.org/wiki/Abstract_factory_patternhttp://en.wikipedia.org/wiki/Creational_patternhttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Concern_(computer_science)http://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Subclass_(computer_science)http://en.wikipedia.org/wiki/Derived_typehttp://en.wikipedia.org/wiki/Object-orientedhttp://en.wikipedia.org/wiki/Computer_programminghttp://en.wikipedia.org/wiki/Object_(computer_science)http://en.wikipedia.org/wiki/Abstraction_(computer_science)http://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/Singleton_(mathematics)http://en.wikipedia.org/wiki/Singleton_patternhttp://en.wikipedia.org/wiki/Method_(computer_science)http://en.wikipedia.org/wiki/Parameterhttp://en.wikipedia.org/wiki/Class_(computer_science)http://en.wikipedia.org/wiki/Object_poolhttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Design_Patterns_(book)http://en.wikipedia.org/wiki/Builder_patternhttp://en.wikipedia.org/wiki/Abstract_factory_pattern
  • 8/7/2019 factorymethodanditeratorpattern

    4/14

    2.2 IMPLEMENTATION

    The pattern basically works as shown below, in the UML diagram:

    The participants classes in this pattern are:

    Product defines the interface for objects the factory method creates.

    Concrete Product implements the Product interface.

    Creator(also referred as Factory because it creates the Product objects) declares the

    method Factory Method, which returns a Product object. May call the generating

    method for creating Product objects

    Concrete Creator overrides the generating method for creating Concrete Product objects

    All concrete products are subclasses of the Product class, so all of them have the same basic

    implementation, at some extent. The Creator class specifies all standard and generic behavior of

    the products and when a new product is needed, it sends the creation details that are supplied by

    the client to the Concrete Creator. Having this diagram in mind, it is easy for us now to produce

    the code related to it. Here is how the implementation of the classic Factory method should look:

    Page 4 of14

  • 8/7/2019 factorymethodanditeratorpattern

    5/14

    public interface Product { }

    public abstract class Creator{

    public void anOperation()

    { Product product = factoryMethod();

    }

    protected abstract Product factoryMethod();

    }

    public class ConcreteProduct implements Product { }

    public class ConcreteCreator extends Creator

    {

    protected Product factoryMethod(){

    return new ConcreteProduct();}

    }

    public class Client{

    public static void main( String arg[] )

    {Creator creator = new ConcreteCreator();

    creator.anOperation();

    }}

    2.3 APPLICABILITY

    The applicability of the factory method is as follows:

    The creation of the object precludes reuse without significantly duplicating code.

    The creation of the object requires access to information or resources not appropriate to

    contain within the composing object.

    The lifetime management of created objects needs to be centralized to ensure consistent

    behavior.

    Page 5 of14

  • 8/7/2019 factorymethodanditeratorpattern

    6/14

    2.4 OTHER BENEFITS

    Although the motivation behind the factory method pattern is to allow subclasses to choose

    which type of object to create, there are other benefits to using factory methods, many of which

    do not depend on sub classing. Therefore, it is common to define "factory methods" that are not

    polymorphic to create objects in order to gain these other benefits. Such methods are often static.

    2.4.1 Descriptive names

    A factory method has a distinct name. In many object-oriented languages, constructors must

    have the same name as the class they are in, which can lead to ambiguity if there is more than

    one way to create an object. Factory methods have no such constraint and can have descriptive

    names. As an example, when complex numbersare created from two real numbers the real

    numbers can be interpreted as Cartesian or polar coordinates, but using factory methods, the

    meaning is clear. When factory methods are used for disambiguation like this, the constructor is

    often made private to force clients to use the factory methods.

    2.4.2 Encapsulation

    Factory methods encapsulate the creation of objects. This can be useful if the creation process isvery complex, for example if it depends on settings in configuration files or on user input.

    Consider as an example a program to readimage filesand makethumbnails out of them. The

    program supports different image formats, represented by a reader class for each format.

    Each time the program reads an image it needs to create a reader of the appropriate type based on

    some information in the file. This logic can be encapsulated in a factory method.

    Page 6 of14

    http://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/Complex_numberhttp://en.wikipedia.org/wiki/Complex_numberhttp://en.wikipedia.org/wiki/Image_filehttp://en.wikipedia.org/wiki/Image_filehttp://en.wikipedia.org/wiki/Image_filehttp://en.wikipedia.org/wiki/Thumbnailhttp://en.wikipedia.org/wiki/Thumbnailhttp://en.wikipedia.org/wiki/Constructor_(computer_science)http://en.wikipedia.org/wiki/Complex_numberhttp://en.wikipedia.org/wiki/Image_filehttp://en.wikipedia.org/wiki/Thumbnail
  • 8/7/2019 factorymethodanditeratorpattern

    7/14

    2.5 SPECIFIC PROBLEMS

    When implementing the Factory Method design pattern some issues may appear:

    Definition of Creator class

    If we apply the pattern to an already written code there may be problems with the way we have

    the Creator class already defined. There are two cases:

    Creator class is abstract and generating method does not have any implementation. In this

    case the ConcreteCreator classes must define their own generation method and this

    situation usually appears in the cases where the Creator class can't foresee what

    ConcreteProduct it will instantiate.

    Creator class is a concrete class, the generating method having a default implementation.

    If this happens, the ConcreteCreator classes will use the generating method for flexibility

    rather than for generation. The programmer will always be able to modify the class of the

    objects that the Creator class implicitly creates, redefining the generation method.

    Factory method is just a particular case of the factory design pattern. In the same time it

    is the most known factory pattern, maybe because it was published in the GoF. In modern

    programming languages the factory with registration is more used.

    2.6 Drawbacks and Benefits

    Here are the benefits and drawbacks of factory method pattern:

    The main reason for which the factory pattern is used is that it introduces a separation

    between the application and a family of classes (it introduces weak coupling instead of

    tight coupling hiding concrete classes from the application). It provides a simple way of

    extending the family of products with minor changes in application code.

    It provides customization hooks. When the objects are created directly inside the class it's

    hard to replace them by objects which extend their functionality. If a factory is used

    instead to create a family of objects the customized objects can easily replace the original

    objects, configuring the factory to create them.

    Page 7 of14

  • 8/7/2019 factorymethodanditeratorpattern

    8/14

    DRAW BACKS:

    There are three limitations associated with the use of the factory method. The first relates

    to refactoring existing code; the other two relate to extending a class.

    1) The first limitation is that refactoring an existing class to use factories breaks existing clients.

    For example, if class Complex was a standard class, it might have numerous clients with code

    like: Complex c = new Complex (-1, 0);

    Once we realize that two different factories are needed, we change the class (to the code shown

    earlier). But since the constructor is now private, the existing client code no longer compiles.

    2) The second limitation is that, since the pattern relies on using a private constructor, the class

    cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be doneif that constructor is private.

    3) The third limitation is that, if we do extend the class (e.g., by making the constructor protected

    this is risky but feasible), the subclass must provide its own re-implementation of all factory

    methods with exactly the same signatures. For example, if class StrangeComplex extends

    Complex, then unless StrangeComplex provides its own version of all factory methods, the call

    StrangeComplex.fromPolar(1, pi) will yield an instance of Complex (the super class) rather than

    the expected instance of the subclass.

    2.7 KNOWN USES

    In ADO.NET, IDbCommand.CreateParameteris an example of the use of factory method

    to connect parallel class hierarchies.

    In Qt, QMainWindow::createPopupMenu is a factory method declared in a framework

    which can be overridden in application code.

    In Java, several factories are used in the javax.xml.parsers package. e.g.javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.

    Page 8 of14

    http://en.wikipedia.org/wiki/Code_refactoringhttp://en.wikipedia.org/wiki/ADO.NEThttp://msdn2.microsoft.com/en-us/library/system.data.idbcommand.createparameter.aspxhttp://en.wikipedia.org/wiki/Qt_(toolkit)http://doc.trolltech.com/4.0/qmainwindow.html#createPopupMenuhttp://en.wikipedia.org/wiki/Java_(programming_language)http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/package-summary.htmlhttp://en.wikipedia.org/wiki/Code_refactoringhttp://en.wikipedia.org/wiki/ADO.NEThttp://msdn2.microsoft.com/en-us/library/system.data.idbcommand.createparameter.aspxhttp://en.wikipedia.org/wiki/Qt_(toolkit)http://doc.trolltech.com/4.0/qmainwindow.html#createPopupMenuhttp://en.wikipedia.org/wiki/Java_(programming_language)http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/package-summary.html
  • 8/7/2019 factorymethodanditeratorpattern

    9/14

    3. ITERATOR PATTERN

    Provide a way to access the elements of an aggregate object sequentially without exposing its

    underlying representation.

    The abstraction provided by the iterator pattern allows you to modify the collection

    implementation without making any changes outside of collection. It enables you to create a

    general purpose GUI component that will be able to iterate through any collection of the

    application.

    3.1 CONCEPT

    In object-oriented programming, the Iterator pattern is a design pattern in which iterators are

    used to access the elements of an aggregate object sequentially without exposing its underlying

    implementation. An Iterator object encapsulates the internal structure of how the iteration occurs.

    For example, a tree,linked list, hash table, and an array all need to be iterated with the methods

    search, sort, and next. Rather than having 12 different methods to manage (one implementation

    for each of the previous three methods in each structure), using the iterator pattern yields just

    seven: one for each class using the iterator to obtain the iterator and one for each of the three

    methods. Therefore, to run the search method on the array, you would call array.search(), which

    hides the call to array.iterator.search().

    Page 9 of14

    http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Iteratorhttp://en.wikipedia.org/wiki/Information_Hidinghttp://en.wikipedia.org/wiki/Tree_(data_structure)http://en.wikipedia.org/wiki/Linked_listhttp://en.wikipedia.org/wiki/Hash_tablehttp://en.wikipedia.org/wiki/Array_data_structurehttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Design_pattern_(computer_science)http://en.wikipedia.org/wiki/Iteratorhttp://en.wikipedia.org/wiki/Information_Hidinghttp://en.wikipedia.org/wiki/Tree_(data_structure)http://en.wikipedia.org/wiki/Linked_listhttp://en.wikipedia.org/wiki/Hash_tablehttp://en.wikipedia.org/wiki/Array_data_structure
  • 8/7/2019 factorymethodanditeratorpattern

    10/14

    3.2 IMPLEMENTATION

    One Real time example of Iterator Pattern is the usage of Remote Controls in Home.Any RemoteControl we use to start pressing up and down and back keys to iterate through the channels.

    What sort of interface can Iterator be in case of Remote Controls?

    One Example Implementation might be:

    public interface Iterator

    {public Channel nextChannel(int currentChannel);

    public Channel previousChannel(int currentChannel);

    }

    The Channel iterator is common for all the remote controls.It's like a specification implemented

    by all the remote control manufacturing companies.

    public ChannelSurfer implements Iterator {

    public Channel nextChannel(int currentChannel) {

    Channel channel=new Channel(currentChannel+1);return channel;

    }

    public Channel previousChannel(int currentChannel) {Channel channel=new Channel(currentChannel-1);return channel;

    }

    }

    public class RemoteControl {

    private ChannelSurfer surfer;

    public RemoteControl() {

    surfer=new ChannelSurfer();

    }

    public Program getProgram(ChannelSurfer surfer) {

    return new Program(surfer.nextChannel());

    }

    }

    public Program {

    Page 10 of14

  • 8/7/2019 factorymethodanditeratorpattern

    11/14

    // ... Some specific implementation of Program class.

    }

    We all know that every channel is associated with program and it's basically the program and not

    the channel number which a user wants to see. This applies that we can apply some logic before

    returning the elements through iterator. Iterator here can also be programmed to return 'the

    programs' straight away rather than returning the channels.

    3.3 APPLICABILITY

    The iterator pattern allows us to:

    Access contents of a collection without exposing its internal structure.

    Support multiple simultaneous traversals of a collection.

    Provide a uniform interface for traversing different collection.

    3.4 SPECIFIC PROBLEMS

    Several problems may appear when collections are added from different threads. First of all let's

    see which the basic steps when using an iterator are:

    Step one: the collection return a new iterator (using in our example the createIterator

    method). Usually this step is not affected when it is used in multithreading environments

    because it returns a new iterator object.

    Step two: The iterator is used for iterating through the objects. Since the iterators are

    different objects this step is not a problematic one in multithreading environments.

    It seems that the iterator does not raise special problems when a collection is used from different

    threads. Of course here we are talking about an "seems". To reformulate the iterator does not

    raise special problems when the collection used from different threads as long the collection is

    not changed.

    Let's analyze each case:

    Page 11 of14

  • 8/7/2019 factorymethodanditeratorpattern

    12/14

    A new element is added to the collection (at the end). The iterator should be aware of the

    new size of the collection and to iterate till the end.

    A new element is added to the collection before the current element. In this case all the

    iterators of the collection should be aware of this.

    The main task when creating a multithreading iterator is to create a robust iterator (that allows

    insertions and deletions without affection transversal). Then the blocks which are changing or

    accessing resources changed by another thread have to be synchronized.

    3.5 KNOWN USES

    Iterators are common in object oriented systems. Most collection class libraries offer iteratiors in

    one form or another.

    Polymorphic iterators and cleanup proxy are provided by the ET++ container classes

    The Unidraw graphical editing framework classes use cursor-based iterators

    Object windows 2.0 provide a class hierarchy of iterators for containers.

    Page 12 of14

  • 8/7/2019 factorymethodanditeratorpattern

    13/14

    4. CONCLUSION

    To conclude this seminar on the note of design patterns is not possible because at least 250

    existing patterns are used in OO world, including Spaghetti which refers to poor coding habits.

    The 23 design patterns by GOF are well known, and more are to be discovered on the way.

    Hence these design patterns help a object oriented programmer to design and overcome the bugs

    that which previously prevailed.

    5. BIBLIOGRAPHY / REFERENCES

    Page 13 of14

  • 8/7/2019 factorymethodanditeratorpattern

    14/14

    http://sourcemaking.com/design_patterns

    http://www.oodesign.com/iterator-pattern.html

    http://en.wikipedia.org/wiki/Design_Patterns

    http://home.earthlink.net/~huston2/dp/factoryMethod.html

    Design Patterns -- Elements of Reusable Object-Oriented Software by GOF.

    The Design Patterns, Java Companion-- by James W. Cooper

    Sun's core J2EE Patterns

    Head first design patterns by Eric Freeman, Elizabeth

    Design patterns explained: a new perspective on object-oriented design By Alan

    Shalloway, James Trott.

    Core J2EE patterns: best practices and design strategies, By Deepak Alur, John Crupi,

    Dan Malks.

    Page 14 of14

    http://sourcemaking.com/design_patternshttp://sourcemaking.com/design_patternshttp://www.oodesign.com/iterator-pattern.htmlhttp://www.oodesign.com/iterator-pattern.htmlhttp://en.wikipedia.org/wiki/Design_Patternshttp://en.wikipedia.org/wiki/Design_Patternshttp://home.earthlink.net/~huston2/dp/factoryMethod.htmlhttp://home.earthlink.net/~huston2/dp/factoryMethod.htmlhttp://www.patterndepot.com/put/8/JavaPatterns.htmhttp://www.patterndepot.com/put/8/JavaPatterns.htmhttp://java.sun.com/blueprints/corej2eepatterns/Patternshttp://sourcemaking.com/design_patternshttp://www.oodesign.com/iterator-pattern.htmlhttp://en.wikipedia.org/wiki/Design_Patternshttp://home.earthlink.net/~huston2/dp/factoryMethod.htmlhttp://www.patterndepot.com/put/8/JavaPatterns.htmhttp://java.sun.com/blueprints/corej2eepatterns/Patterns