1 DESIGN PATTERN AND ITS APPLICATIONS B.Tech Major Project Report BY GAYATRI THAKUR SWEKSHA PANDEY DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING NATIONAL INSTITUTE OF TECHNOLOGY RAIPUR- CG (INDIA) MAY, 2015
2 DESIGN PATTERN AND ITS APPLICATIONS A Major Project Report Submitted in partial fulfillment of the requirement for the award of the degree of Bachelor of Technology in COMPUTER SC. & ENGINEERING BY GAYATRI THAKUR SWEKSHA PANDEY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING NATIONAL INSTITUTE OF TECHNOLOGY RAIPUR- CG (INDIA) MAY, 2015
3 CERTIFICATE I hereby certify that the work which is being presented in the B.Tech. Major Project Report entitled “DESIGN PATTERN AND ITS APPLICATIONS”, in fulfillment of the requirements for the award of the Bachelor of Technology in Computer Sc. & Engineering and submitted to the Department of Computer Sc. & Engineering of National Institute of Technology Raipur is an authentic record of my own work carried out during a period from Jan 2015 to may 2015 under the supervision of HOD Dr. Naresh Kumar Nagwani, CSE Department. The matter presented in this thesis has not been submitted by me for the award of any other degree elsewhere. Signature of Candidates SWEKSHA PANDEY R.No. 11115041 GAYATRI THAKUR R.No. 11115028 This is to certify that the above statement made by the candidate is correct to the best of my knowledge. DATE: Signature of Supervisor(s) Head of department Dr. Naresh Kumar Nagwani Head Computer Sc. & Engineering Department National Institute of Technology Raipur CG
4 ABSTRACT Design patterns are solutions to general problems that software developers faced during software development. Design patterns represent the best practices used by experienced object-oriented software developers. In our project Design pattern and its applications we have implemented several softwares by taking advantages of design patterns. Design pattern is more useful if the language we are using for software development is object oriented programming language. So we have used java and developed several smaller softwares like calculator using factory pattern, degree Fahrenheit conversion using adapter pattern, matching colored shapes with its name using bridge pattern and many more. We have followed Gang of four [Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides] classification of design pattern. Main purpose of the project was to develop an interactive platform for learning design pattern. So we have made a website using php for learning design pattern and all the running applications are attached to this tutorial. User of this tutorial can learn design pattern and he/she can understand its advantages with the help of running applications attached to it. Complete code of each implementation is also linked to this tutorial. So it is easier to understand every design pattern, its type and applications.
5 ACKNOWLEDGEMENT The completion of this project would have not been possible without the help of others. First of all we would like to thank people who gave us strength and ability to complete this project. We express our heartily acknowledgement to our project guide Dr. N. K. Nagwani, Head of Computer Science & Engineering Department, NIT Raipur for providing us the opportunity and freedom to work on this project and also for being so inspiring and supportive. We are also thankful to Akanksha Verma, faculty of computer science & engineering department for helping and supporting us throughout the project. The success and accomplishment of this report stems from efforts and dedication offered by faculty members whose support was either direct or indirect during our project work. We thank them all for their devotion and generosity. We are also thankful to all the persons who have helped us in any possible way towards the accomplishment of our work. Sweksha Pandey Gayatri Thakur
6 TABLE OF CONTENTS Certificate iii Abstract iv Acknowledgement v List of figures vi Chapter 1 Introduction 1 1.1 Purpose and Scope 1 1.2 Features and Constraints 2 Chapter 2 Design Pattern 3 2.1 Creational Design Pattern 4 2.2 Structural Design Pattern 5 2.3 Behavioral Design Pattern 5 Chapter 3 Implementation of applications 7 3.1 Singleton Design Pattern 7 3.2 Factory Method 8 3.3 Abstract Factory Method 9 3.4 Adapter Pattern 10 3.5 Decorate Pattern 11 3.6 Bridge Pattern 13 3.7 Façade Pattern 3.8 Template Pattern 3.9 Chain Responsibility design pattern 21 3.10 Mediator Design Pattern 22 3.11 Strategy Design Pattern 23 3.12 Iterator Design Pattern 24 3.13 Interpreter Design Pattern 25 3.14 Observer design Pattern 27 Chapter 4 Tutorial 28 Chapter 5 Conclusion And Scope 31 References 32
7 LIST OF FIGURES Fig. 3.1.1 Initial window of software for singleton Fig. 3.1.2 Requesting instances of server Fig. 3.2.1 Calculator for unary and binary operations Fig. 3.3.1 implementation of abstract factory Fig. 3.4.1 Fahrenheit to Celsius conversion Fig. 3.4.2 Celsius to Fahrenheit conversion Fig. 3.5.1 decorator pattern example after first description Fig. 3.5.2 decorator pattern example after all the descriptions Fig. 3.6.1 Initial window of bridge pattern example Fig. 3.6.2 Bridge pattern window after some operation Fig. 3.7.1 façade pattern calculates 6th root Fig. 3.7.2 Façade pattern calculates 9th root Fig. 3.8.1 template for cricket Fig. 3.8.2 template for football and cricket Fig. 3.7.1 Chain Responsibility Design pattern example Fig. 3.8.1 Mediator design pattern Fig. 3.9.1 Strategy Design Pattern example 1 Fig. 3.9.2 Strategy Design Pattern example 2 Fig. 3.10.1 Iterator Design Pattern example Fig.3.11.1 Interpreter Design Pattern example Fig 3.12.1 Observer Design Pattern example Fig. 4.1 home page of tutorial Fig. 4.2 Introduction page of tutorial Fig. 4.3 Singleton pattern in tutorial
8 1. INTRODUCTION In simple words design patterns are solution to common problems that is faced by software developers but if we go in deep it is very important term that should be known by every software developer. It's the job that must be identified and understood before the tool can be chosen for its implementation. There are 23 design patterns that can be used or can be applied during software development. The key isn’t necessarily to learn the patterns themselves. The key is to learn to identify the scenarios and problems which the patterns are meant to address. Then applying the pattern is simply a matter of using the right tool for the job. Often we face problems during software development in which no combination of design patterns can be used to solve that problem. At that point more attention needs to be given to the problem rather than the solution. 1.1 Purpose and scope Not all solutions fit neatly into an existing design pattern and adopting a pattern may mean that we muddy the cleanness of your solution. The key is try to keep your code clean, modular and readable and make sure your classes aren't tightly coupled. Obviously, if we pick the correct design pattern for a particular scenario then we won't have a problem, however picking the correct one is easier said than done. Main objective of our project is to learn design pattern and to make a tutorial for learning design pattern so that the user can understand perfect use of design pattern and can understand problem and its associated design pattern to solve that particular problem. Several software are attached to the tutorial and user can understand main logic behind the software for which codes are given in the tutorial itself. However complete code can also be obtained by the link provided below every running software.
9 1.2 Features and constraints Applications developed are very smaller applications and can also be developed without use of design pattern. Main motive was to learn the use of design pattern from smaller applications and to get a idea about how to apply it in larger applications. For example in the tutorial adapter pattern is used to implement conversion of degree Celsius to Fahrenheit. Same idea can also be applied for implementation of a media player that can play different types of song eg: mp3, mp4, .wav etc. Factory pattern is used to implement a simple calculator in our tutorial but same idea can be applied to implement paint that can draw several shapes based on the button we click. The tutorial we have developed is in php and all the java applications are embedded as applet in it. Video at the home page of the code explains use and functioning of tutorial. Hence this is an interactive tutorial that best explains everything about design pattern.
10 2. DESIGN PATTERN Design pattern takes advantages of object oriented programming language to provide solutions to common problem that may be faced by software developer during software development. There are three types of design patterns- 1. Creational design pattern 2. Structural design pattern 3. Behavioral design pattern These types are further classified in several design patterns that is given in preceding sections. 2.1 Creational Design Pattern These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. These design patterns are used in situations when basic form of object creation could result in design problems or increase complexity of a code base. This design pattern tries to create objects in a manner suitable to the situation. Creational design patterns solve this problem by somehow controlling this object creation. Classification of creational design pattern is given below: (i).Singleton A class that can be instantiated only once (ii)Factory Method It creates an instance of several derived classes.
11 (iii)Abstract Factory Method It creates an instance of several families of classes (iv)Builder Pattern It separates object construction from its representation (v)Prototype Pattern A fully initialized instance to be copied or cloned 2.2 Structural design pattern These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. It describes how objects and classes can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe abstraction with the help of inheritance and how it can be used to provide more useful program interface. Object patterns, on other hand, describe how objects can be associated and composed to form larger, more complex structures. There are seven structural patterns described. They are as follows: (i). Adapter Pattern It is used so that two unrelated interfaces can work together. (ii). Bridge Pattern It is used where we need to decouple an abstraction from its implementation so that the two can vary independently. (iii). Composite Pattern Composite pattern is used where we need to treat a group of objects in similar way as a single object. (iv). Decorator Pattern Decorator pattern allows to add new functionality to an existing object without altering its structure. (v). Facade Pattern Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
12 (vi). Flyweight Pattern Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. (vii). Proxy Pattern In Proxy pattern, a class represents functionality of another class. 2.3 Behavioral DesignPattern Behavioral design pattern explain how objects interact . It describes how different objects and classes send message to each other. It concern with identifying common interaction between objects and realizing these. This increase the flexibility by letting them talk to each other but still retaining the desired loose coupling between these objects . Behavior design pattern use inheritance distribute behavior between classes. Following are types of behavioral design pattern 1. Template Method Pattern 2. Mediator Pattern 3. Chain Responsibility Pattern 4. Observer Pattern 5. Strategy Pattern 6. Command Pattern 7. State Pattern 8. Visitor Pattern 9. Iterator Pattern 10 Momento Pattern
13 3. IMPLEMENTATION OF APPLICATIONS In this section implementation of all the softwares is considered starting from the singleton class of creational design pattern. 3.1 Singleton design pattern This design pattern is used where we want only single instance of the class or we want to avoid creation of multiple instances of a particular class. Here we use this class to create an application in which request for first instance of server is granted but when we tried creating second instance of that class then it shows error stating that it is not possible to create multiple instances of the server because server is using singleton class. Fig. 3.1.1 Initial window of software for singleton Start Server button is used for starting the server and next two buttons are used for requesting instances of server. We will see in the next figure that first instance can be granted but request for second instance is not entertained and it shows error message.
14 Fig. 3.1.2 Requesting instances of server 3.2 Factory method Factory method is used to create instance of several derived classes. A factory class instantiates and returns a particular type of object based on data passed to the factory. The different types of objects that are returned from a factory typically are subclasses of a common parent class. Here is a simple example of factory pattern in which a simple calculator is developed. It has a factory class consisting of all the operations and a click on any of the operators sends a request for creating object for that operator and that object is used for calling the operations for corresponding operator. Fig. 3.2.1 shows this example:
15 Fig. 3.2.1 Calculator for unary and binary operations 3.3 Abstract Factory Method Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. In Abstract Factory pattern an interface is responsible for creating a factory of related interface is responsible for creating a factory of related objects without explicitly specifying their classes. Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. In Abstract Factory pattern an interface is responsible for creating a factory of related interface is responsible for creating a factory of related objects without explicitly specifying their classes. A simple example of the abstract factory design is shown here:
16 Fig. 3.3.1 implementation of abstract factory 3.4 Adapter Pattern Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class which is responsible to joint functionalities of independent or incompatible interfaces. Here is an example of adapter class that combines features of celcius and fahrenheit.TemperatureClassReporter is a class adapter. It extends CelciusReporter (the adaptee) and implements TemperatureInfo (the target interface). If a temperature is in Celcius, TemperatureClassReporter utilizes the temperatureInC value from CelciusReporter. Fahrenheit requests are internally handled in Celsius.
17 Fig. 3.4.1 Fahrenheit to Celsius conversion Fig. 3.4.2 Celsius to Fahrenheit conversion 3.5 Decorator Pattern Decorator pattern allows a user to add new functionality to an existing object without altering its structure.This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.We can explain decorator pattern by simple example of creating
18 animal interface first then adding properites to it one by one. For example it has leg ,wing or it can sing and many more properties according to the needs. Fig. 3.5.1 decorator pattern example after first description Further click on second description, third description and fourth description concatenates various characteristics to the string. Programmatically it adds various characteristics to class using features of object oriented programming languages. Fig. 3.5.2 decorator pattern example after all the descriptions 3.6 Bridge Pattern Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. For example we can create a bridge between shape and color of a paint and we can choose color and shape independently for drawing.
19 An example of it is given below in which we are choosing shape and color and a String tells us the correct match from the given shapes. Fig. 3.6.1 Initial window of bridge pattern example Fig. 3.6.2 Bridge pattern window after some operation
20 3.7 Façade Pattern In the facade pattern, a facade classes is used to provide a single interface to set of classes. The facade simplifies a clients interaction with a complex system by localizing the interactions into a single interface. As a result, the client can interact with a single object rather than being required to interact directly in complicated ways with the objects that make up the subsystem. For example if we want to find nth root of a number by hiding its computation complexity from the user then writing code in a single class may increase complexity of that class and it will be harder for a user to interact with that class. Following is the example which can calculate root of a number by combining features of multiple classes. Fig. 3.7.1 façade pattern calculates 6th root Mathematical fact that sqrt(sqrt(n)) will give fourth root of a number and sqrt(cbrt(n)) will give 6th root of a number is easier to understand. Same principle is applied here to calculate various roots of number and it can be understand that we can get solution of complex problems just by combining features of several classes. This applet calculates all the 6 root of a number as shown in the applet window. Main two methods available are for square root and cube root only. Combine these two in
21 different order we are able to calculate other roots. For example square root and cube root together give sixth root of any number. Applying cube root twice gives us ninth root of the number. Figure shows calculation of 6th and 9th root of a number Fig. 3.7.2 Façade pattern calculates 9th root 3.8 Template Pattern In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category. For example we can create a common template for any game in which steps for the game will similar and these steps will be defined in abstract class. No matter how we implement that class order of occurrence of events will be same because of the order of declaration of events in abstract class. Below is a example which shows steps involved in Cricket and Football. In the figure below template for cricket appears and it contains the same order as order described in abstract class.
22 Fig. 3.8.1 template for cricket Steps involve for playing football is similar to cricket so we can use same abstract class for football also. Following screenshot explains similarity between both the templates. Fig. 3.8.2 template for football and cricket 3.9 Chain Responsibility Design pattern Chain responsibility design pattern gives opportunity to object to handle request. Actually what happen, sender sends request to the chain of objects , and each object handle specific request , chain responsibility gives to multiple objects a opportunity to handle request. Like Gmail account different Handlers to handle specific type of email that handle primary messages ,social messages, forum messages in a chain.
23 Another example is to handle different numbers like positive, negative and zero numbers. Fig. 3.7.1 Chain Responsibility Design pattern example To handle positive, negative and zero numbers there is three buttons first button to handle negative number, second button to handle positive number and zero number handled by third button . JLabel is used to show messages. User sends request through TextField and if number is greater than zero then it will send request to each handler to handle request. So, value is suppose 10 then it will handle by positive handler button , and if value is suppose -10 then it will handle by negative handler button and zero number by zero handler button. If we try to handle -10 by positive handler button then handler will discard to requests and it will show message Negative Number will Not handled by this positive handler button. We can use this application in shopping cart where customer requests for any item and this request handled by specific handler 3.8 Mediator design pattern When to object trying to communicate with each other some times it become more complex , and complexity may be because of structure of object or type of object .So, mediator design pattern provides loose coupling between objects to reduce complexity among multiple objects or classes ,So it provides a class which normally handle all communication between different classes or different objects. For example suppose there is a class to handle messages , users send messages to this class and it’s responsibility of this class to show this messages to all users so, there is a class to handle user objects and another class uses this objects to show communication between them.
24 Fig. 3.8.1 Mediator design pattern example First of all one user will register his name to communicate with another user and through given text field and send message to the class which handle this messages, will show his messages then another user will register his name and then sends his messages and class will show this messages to another users. 3.9 Strategy DesignPattern In strategy pattern , a class behavior or algorithm can change at run time. In strategy pattern we create object which represent various strategy. Strategy pattern can encapsulate various algorithms in a one class to change algorithm at run time . For example a file compressor ,there is a compressor strategy class which select different algorithms at run time to compress files. Fig. 3.9.1 Strategy Design Pattern example 1
25 This compressor strategy class handle multiple algorithms and can execute one of them at run time. Compressor button is used to handle class which handle multiple algorithms and at run time can execute either zip, gzip or may be rar to compress file. Another feature is it can change behavior of class at run time. For example a class context which change it’s behavior at run time , by either executes addition operation or subtraction or multiplication of numbers. Fig. 3.9.2 Strategy Design Pattern example 2 There is three TextFieds to handle inputs and outputs and three operations will given here which will change by strategy class at run time. So it maintain complexity of software. When we build a large software ,software developer care about complexity and execution time of algorithms so in this case it’s beneficial to use strategy design pattern in place using large set of switch cases to execute different strategies at run time, Because software developer always trying to prohibit to use switch cases and always trying to eliminate more execution time. So it’s better to use strategy pattern for this purpose by encapsulates multiples algorithms or change execution at run time. 3.10 Iterator DesignPattern When a software developer develop large application and there is a problem creates related with accessing date from large collections of data, then it is beneficial to use Iterator design pattern, in terms of to access a data from large collection, it accesses data from collection with out exposing data structure of elements . For example, channel collections of hindi , English ,French with different frequencies are decoupled because of iterator design pattern. How ever this pattern also used for classification of attributes, for example in this GUI which is given below for hindi
26 channel it separates it by frequency also to English, French channel classified by frequency. Fig. 3.10.1 Iterator Design Pattern example There is three buttons for English channel, hindi channel, French channel and when we click one of them ,suppose English button then it sends request to handler to classify each English channel by frequency from another channels and show Dialog- box used to show messages, and same kind of stuff we do for hindi channel, French channel. However this property can used in classification of attributes like apriori in data mining, Iterator design pattern search for english channel along with frequency, and classify all channels according to the frequency. 3.11 Interpreter Design Pattern Iterator design pattern is used to map a value to a given expression or a grammar expression may be complex ,like postfix notation and infix expression in data structure, this pattern used to evaluate it’s value. Interpreter design pattern map a domain to a language,the language to a grammar a grammar to a object oriented design. Defining a language as a simple language grammar, representing domain rules as a language sentence, and interpreting these sentence to solve the problem. Pattern uses a class to represent each grammar rule. for example suppose there is an digits in roman, by intepreter design pattern it will interpret in to English digits. It interpret complex expression or grammar in to single value. It's GUI representation is given below:-
27 Fig. 3.11.1 parser from roman to English digit This GUI uses a button to parse given roman number into digits, so it content a text field through user gives input and when clicking at parse button it assign digit. Context class handles input and expression abstract class handle expression. Class handle objects to request to evaluate expressions value. 3.12 Observer DesignPattern One famous example we know of observer design pattern publisher/subscriber which hold one-to-many relationship between objects, JMS (java message services) and socket programming is way to implement this relation, it maintain publisher/subscriber servers to publish and subscribes messages. However Observer design pattern is used to implement one-to-many relation between objects, such as if one object is modified ,its dependent objects are to be notify automatically for example:-suppose subject and concrete class object to show observer pattern in action- Fig 3.12.1 observer design pattern example In this example there is three observers hexadecimal, octal, binary and suppose in first time state change occurs when input given suppose 234 then hexadecimal will observe EA, Octal observer will observe 352 and Binary observer will observe
28 11101010, in same way when user provides different input, observer will observe different output as explain in above line.
29 4. TUTORIAL We have developed a tutorial in php for design pattern and all the applications mentioned above are attached to the tutorial so that it can be easy for the user to understand each and every design pattern properly. Code for each attached application is linked along with that application a link is given below the application from where it can be viewed. A video is attached at the home page which can explain the functionality and use of the tutorial. Below is the screen shot of the home page : Fig. 4.1 home page of tutorial Home page contains basic definition of design pattern and link to further pages are given at this page for further study. Video at this page explains functionality and basic use of this tutorial.
30 Fig. 4.2 Introduction page of tutorial Now each design pattern is explained individually and its application is attached to it. Below is the screen shot of the tutorial that contains attached singleton pattern.
31 Fig. 4.3 Singleton pattern in tutorial
32 5. CONCLUSION AND SCOPE After analyzing and studying each design pattern we came to know that knowledge of design pattern is necessary if we want to develop a software with tightly coupled classes, modular and readable code. The key is to learn to identify the scenarios and problems in software development which the patterns are meant to address. Often we face problems during software development in which no combination of design patterns can be used to solve that problem. At that point more attention needs to be given to the problem rather than the solution. So we came to the conclusion that each and every design pattern if studied properly can be advantageous at many places in software development where we stuck at some situation and unable to come out of that because of lack of ideas to solve that problem. Sometimes it may feel that design pattern increase complexity of code and software and sometimes it is true. Because problems of smaller applications have several solutions which are easier to implement and less complex than design pattern but if we are developing a complex software with many lines of code then it very impractical to start coding randomly and often we end up in the middle of nowhere and our code becomes so unreadable . Main scope of studying design pattern is in software development and with a collaborative study we learn to take advantages of object oriented programming language in terms of design pattern. We learn to understand problems and its solution. For example suppose developer A has developed a vlc media player application but if user clicks on the icon twice by mistake then it opens two window of vlc media player. Obviously it is impractical to watch something in two windows and user has to close one of them manually. So developer would like to enhance this application adding a feature in which multiple clicks on the icon opens only a single window of vlc media player. But he has no idea how to add this functionality to an existing software and here comes the use of singleton design pattern. Adding a singleton class to his media player can ensure that only one instance of that media player can be created irrespective of the request for multiple instances.
33 REFERENCES Books [1]Design Pattern: Elements of Reusable object-oriented Software By :Erich Gamma, Richard Helm ,Ralph Johnson, John M.Vlissides (GOF) [2]Head First design Patterns, By: Elisabeth Freeman, Eric Freeman, BertBates, Kathy Sierra [3]Pattern Hatching: Design Patterns Applied By: John M.Vlissides [4]Refactoring to Patterns, By: Joshua Kerievsky [5]Patterns of Enterprise Application Architecture By:Martin Fowler Journals [1]Douglas A.Lyon and Francisco castellanos “The parametric singleton design pattern”, in journal of object technology, March- April 2007 http://www.jot.fm/issues/issue_2007_03/column2 Thesis [1]The “Gang Of Four” Pattern Implemented in java, Mater’s Thesis [2]Object Oriented Design Pattern, By Marcel Birkner

Design pattern application

  • 1.
    1 DESIGN PATTERN ANDITS APPLICATIONS B.Tech Major Project Report BY GAYATRI THAKUR SWEKSHA PANDEY DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING NATIONAL INSTITUTE OF TECHNOLOGY RAIPUR- CG (INDIA) MAY, 2015
  • 2.
    2 DESIGN PATTERN ANDITS APPLICATIONS A Major Project Report Submitted in partial fulfillment of the requirement for the award of the degree of Bachelor of Technology in COMPUTER SC. & ENGINEERING BY GAYATRI THAKUR SWEKSHA PANDEY DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING NATIONAL INSTITUTE OF TECHNOLOGY RAIPUR- CG (INDIA) MAY, 2015
  • 3.
    3 CERTIFICATE I hereby certifythat the work which is being presented in the B.Tech. Major Project Report entitled “DESIGN PATTERN AND ITS APPLICATIONS”, in fulfillment of the requirements for the award of the Bachelor of Technology in Computer Sc. & Engineering and submitted to the Department of Computer Sc. & Engineering of National Institute of Technology Raipur is an authentic record of my own work carried out during a period from Jan 2015 to may 2015 under the supervision of HOD Dr. Naresh Kumar Nagwani, CSE Department. The matter presented in this thesis has not been submitted by me for the award of any other degree elsewhere. Signature of Candidates SWEKSHA PANDEY R.No. 11115041 GAYATRI THAKUR R.No. 11115028 This is to certify that the above statement made by the candidate is correct to the best of my knowledge. DATE: Signature of Supervisor(s) Head of department Dr. Naresh Kumar Nagwani Head Computer Sc. & Engineering Department National Institute of Technology Raipur CG
  • 4.
    4 ABSTRACT Design patterns aresolutions to general problems that software developers faced during software development. Design patterns represent the best practices used by experienced object-oriented software developers. In our project Design pattern and its applications we have implemented several softwares by taking advantages of design patterns. Design pattern is more useful if the language we are using for software development is object oriented programming language. So we have used java and developed several smaller softwares like calculator using factory pattern, degree Fahrenheit conversion using adapter pattern, matching colored shapes with its name using bridge pattern and many more. We have followed Gang of four [Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides] classification of design pattern. Main purpose of the project was to develop an interactive platform for learning design pattern. So we have made a website using php for learning design pattern and all the running applications are attached to this tutorial. User of this tutorial can learn design pattern and he/she can understand its advantages with the help of running applications attached to it. Complete code of each implementation is also linked to this tutorial. So it is easier to understand every design pattern, its type and applications.
  • 5.
    5 ACKNOWLEDGEMENT The completion ofthis project would have not been possible without the help of others. First of all we would like to thank people who gave us strength and ability to complete this project. We express our heartily acknowledgement to our project guide Dr. N. K. Nagwani, Head of Computer Science & Engineering Department, NIT Raipur for providing us the opportunity and freedom to work on this project and also for being so inspiring and supportive. We are also thankful to Akanksha Verma, faculty of computer science & engineering department for helping and supporting us throughout the project. The success and accomplishment of this report stems from efforts and dedication offered by faculty members whose support was either direct or indirect during our project work. We thank them all for their devotion and generosity. We are also thankful to all the persons who have helped us in any possible way towards the accomplishment of our work. Sweksha Pandey Gayatri Thakur
  • 6.
    6 TABLE OF CONTENTS Certificateiii Abstract iv Acknowledgement v List of figures vi Chapter 1 Introduction 1 1.1 Purpose and Scope 1 1.2 Features and Constraints 2 Chapter 2 Design Pattern 3 2.1 Creational Design Pattern 4 2.2 Structural Design Pattern 5 2.3 Behavioral Design Pattern 5 Chapter 3 Implementation of applications 7 3.1 Singleton Design Pattern 7 3.2 Factory Method 8 3.3 Abstract Factory Method 9 3.4 Adapter Pattern 10 3.5 Decorate Pattern 11 3.6 Bridge Pattern 13 3.7 Façade Pattern 3.8 Template Pattern 3.9 Chain Responsibility design pattern 21 3.10 Mediator Design Pattern 22 3.11 Strategy Design Pattern 23 3.12 Iterator Design Pattern 24 3.13 Interpreter Design Pattern 25 3.14 Observer design Pattern 27 Chapter 4 Tutorial 28 Chapter 5 Conclusion And Scope 31 References 32
  • 7.
    7 LIST OF FIGURES Fig.3.1.1 Initial window of software for singleton Fig. 3.1.2 Requesting instances of server Fig. 3.2.1 Calculator for unary and binary operations Fig. 3.3.1 implementation of abstract factory Fig. 3.4.1 Fahrenheit to Celsius conversion Fig. 3.4.2 Celsius to Fahrenheit conversion Fig. 3.5.1 decorator pattern example after first description Fig. 3.5.2 decorator pattern example after all the descriptions Fig. 3.6.1 Initial window of bridge pattern example Fig. 3.6.2 Bridge pattern window after some operation Fig. 3.7.1 façade pattern calculates 6th root Fig. 3.7.2 Façade pattern calculates 9th root Fig. 3.8.1 template for cricket Fig. 3.8.2 template for football and cricket Fig. 3.7.1 Chain Responsibility Design pattern example Fig. 3.8.1 Mediator design pattern Fig. 3.9.1 Strategy Design Pattern example 1 Fig. 3.9.2 Strategy Design Pattern example 2 Fig. 3.10.1 Iterator Design Pattern example Fig.3.11.1 Interpreter Design Pattern example Fig 3.12.1 Observer Design Pattern example Fig. 4.1 home page of tutorial Fig. 4.2 Introduction page of tutorial Fig. 4.3 Singleton pattern in tutorial
  • 8.
    8 1. INTRODUCTION In simplewords design patterns are solution to common problems that is faced by software developers but if we go in deep it is very important term that should be known by every software developer. It's the job that must be identified and understood before the tool can be chosen for its implementation. There are 23 design patterns that can be used or can be applied during software development. The key isn’t necessarily to learn the patterns themselves. The key is to learn to identify the scenarios and problems which the patterns are meant to address. Then applying the pattern is simply a matter of using the right tool for the job. Often we face problems during software development in which no combination of design patterns can be used to solve that problem. At that point more attention needs to be given to the problem rather than the solution. 1.1 Purpose and scope Not all solutions fit neatly into an existing design pattern and adopting a pattern may mean that we muddy the cleanness of your solution. The key is try to keep your code clean, modular and readable and make sure your classes aren't tightly coupled. Obviously, if we pick the correct design pattern for a particular scenario then we won't have a problem, however picking the correct one is easier said than done. Main objective of our project is to learn design pattern and to make a tutorial for learning design pattern so that the user can understand perfect use of design pattern and can understand problem and its associated design pattern to solve that particular problem. Several software are attached to the tutorial and user can understand main logic behind the software for which codes are given in the tutorial itself. However complete code can also be obtained by the link provided below every running software.
  • 9.
    9 1.2 Features andconstraints Applications developed are very smaller applications and can also be developed without use of design pattern. Main motive was to learn the use of design pattern from smaller applications and to get a idea about how to apply it in larger applications. For example in the tutorial adapter pattern is used to implement conversion of degree Celsius to Fahrenheit. Same idea can also be applied for implementation of a media player that can play different types of song eg: mp3, mp4, .wav etc. Factory pattern is used to implement a simple calculator in our tutorial but same idea can be applied to implement paint that can draw several shapes based on the button we click. The tutorial we have developed is in php and all the java applications are embedded as applet in it. Video at the home page of the code explains use and functioning of tutorial. Hence this is an interactive tutorial that best explains everything about design pattern.
  • 10.
    10 2. DESIGN PATTERN Designpattern takes advantages of object oriented programming language to provide solutions to common problem that may be faced by software developer during software development. There are three types of design patterns- 1. Creational design pattern 2. Structural design pattern 3. Behavioral design pattern These types are further classified in several design patterns that is given in preceding sections. 2.1 Creational Design Pattern These design patterns provides way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case. These design patterns are used in situations when basic form of object creation could result in design problems or increase complexity of a code base. This design pattern tries to create objects in a manner suitable to the situation. Creational design patterns solve this problem by somehow controlling this object creation. Classification of creational design pattern is given below: (i).Singleton A class that can be instantiated only once (ii)Factory Method It creates an instance of several derived classes.
  • 11.
    11 (iii)Abstract Factory Method Itcreates an instance of several families of classes (iv)Builder Pattern It separates object construction from its representation (v)Prototype Pattern A fully initialized instance to be copied or cloned 2.2 Structural design pattern These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities. It describes how objects and classes can be combined to form larger structures. The difference between class patterns and object patterns is that class patterns describe abstraction with the help of inheritance and how it can be used to provide more useful program interface. Object patterns, on other hand, describe how objects can be associated and composed to form larger, more complex structures. There are seven structural patterns described. They are as follows: (i). Adapter Pattern It is used so that two unrelated interfaces can work together. (ii). Bridge Pattern It is used where we need to decouple an abstraction from its implementation so that the two can vary independently. (iii). Composite Pattern Composite pattern is used where we need to treat a group of objects in similar way as a single object. (iv). Decorator Pattern Decorator pattern allows to add new functionality to an existing object without altering its structure. (v). Facade Pattern Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
  • 12.
    12 (vi). Flyweight Pattern Flyweightpattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. (vii). Proxy Pattern In Proxy pattern, a class represents functionality of another class. 2.3 Behavioral DesignPattern Behavioral design pattern explain how objects interact . It describes how different objects and classes send message to each other. It concern with identifying common interaction between objects and realizing these. This increase the flexibility by letting them talk to each other but still retaining the desired loose coupling between these objects . Behavior design pattern use inheritance distribute behavior between classes. Following are types of behavioral design pattern 1. Template Method Pattern 2. Mediator Pattern 3. Chain Responsibility Pattern 4. Observer Pattern 5. Strategy Pattern 6. Command Pattern 7. State Pattern 8. Visitor Pattern 9. Iterator Pattern 10 Momento Pattern
  • 13.
    13 3. IMPLEMENTATION OFAPPLICATIONS In this section implementation of all the softwares is considered starting from the singleton class of creational design pattern. 3.1 Singleton design pattern This design pattern is used where we want only single instance of the class or we want to avoid creation of multiple instances of a particular class. Here we use this class to create an application in which request for first instance of server is granted but when we tried creating second instance of that class then it shows error stating that it is not possible to create multiple instances of the server because server is using singleton class. Fig. 3.1.1 Initial window of software for singleton Start Server button is used for starting the server and next two buttons are used for requesting instances of server. We will see in the next figure that first instance can be granted but request for second instance is not entertained and it shows error message.
  • 14.
    14 Fig. 3.1.2 Requestinginstances of server 3.2 Factory method Factory method is used to create instance of several derived classes. A factory class instantiates and returns a particular type of object based on data passed to the factory. The different types of objects that are returned from a factory typically are subclasses of a common parent class. Here is a simple example of factory pattern in which a simple calculator is developed. It has a factory class consisting of all the operations and a click on any of the operators sends a request for creating object for that operator and that object is used for calling the operations for corresponding operator. Fig. 3.2.1 shows this example:
  • 15.
    15 Fig. 3.2.1 Calculatorfor unary and binary operations 3.3 Abstract Factory Method Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. In Abstract Factory pattern an interface is responsible for creating a factory of related interface is responsible for creating a factory of related objects without explicitly specifying their classes. Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. In Abstract Factory pattern an interface is responsible for creating a factory of related interface is responsible for creating a factory of related objects without explicitly specifying their classes. A simple example of the abstract factory design is shown here:
  • 16.
    16 Fig. 3.3.1 implementationof abstract factory 3.4 Adapter Pattern Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces. This pattern involves a single class which is responsible to joint functionalities of independent or incompatible interfaces. Here is an example of adapter class that combines features of celcius and fahrenheit.TemperatureClassReporter is a class adapter. It extends CelciusReporter (the adaptee) and implements TemperatureInfo (the target interface). If a temperature is in Celcius, TemperatureClassReporter utilizes the temperatureInC value from CelciusReporter. Fahrenheit requests are internally handled in Celsius.
  • 17.
    17 Fig. 3.4.1 Fahrenheitto Celsius conversion Fig. 3.4.2 Celsius to Fahrenheit conversion 3.5 Decorator Pattern Decorator pattern allows a user to add new functionality to an existing object without altering its structure.This type of design pattern comes under structural pattern as this pattern acts as a wrapper to existing class.This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact.We can explain decorator pattern by simple example of creating
  • 18.
    18 animal interface firstthen adding properites to it one by one. For example it has leg ,wing or it can sing and many more properties according to the needs. Fig. 3.5.1 decorator pattern example after first description Further click on second description, third description and fourth description concatenates various characteristics to the string. Programmatically it adds various characteristics to class using features of object oriented programming languages. Fig. 3.5.2 decorator pattern example after all the descriptions 3.6 Bridge Pattern Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. For example we can create a bridge between shape and color of a paint and we can choose color and shape independently for drawing.
  • 19.
    19 An example ofit is given below in which we are choosing shape and color and a String tells us the correct match from the given shapes. Fig. 3.6.1 Initial window of bridge pattern example Fig. 3.6.2 Bridge pattern window after some operation
  • 20.
    20 3.7 Façade Pattern Inthe facade pattern, a facade classes is used to provide a single interface to set of classes. The facade simplifies a clients interaction with a complex system by localizing the interactions into a single interface. As a result, the client can interact with a single object rather than being required to interact directly in complicated ways with the objects that make up the subsystem. For example if we want to find nth root of a number by hiding its computation complexity from the user then writing code in a single class may increase complexity of that class and it will be harder for a user to interact with that class. Following is the example which can calculate root of a number by combining features of multiple classes. Fig. 3.7.1 façade pattern calculates 6th root Mathematical fact that sqrt(sqrt(n)) will give fourth root of a number and sqrt(cbrt(n)) will give 6th root of a number is easier to understand. Same principle is applied here to calculate various roots of number and it can be understand that we can get solution of complex problems just by combining features of several classes. This applet calculates all the 6 root of a number as shown in the applet window. Main two methods available are for square root and cube root only. Combine these two in
  • 21.
    21 different order weare able to calculate other roots. For example square root and cube root together give sixth root of any number. Applying cube root twice gives us ninth root of the number. Figure shows calculation of 6th and 9th root of a number Fig. 3.7.2 Façade pattern calculates 9th root 3.8 Template Pattern In Template pattern, an abstract class exposes defined way(s)/template(s) to execute its methods. Its subclasses can override the method implementation as per need but the invocation is to be in the same way as defined by an abstract class. This pattern comes under behavior pattern category. For example we can create a common template for any game in which steps for the game will similar and these steps will be defined in abstract class. No matter how we implement that class order of occurrence of events will be same because of the order of declaration of events in abstract class. Below is a example which shows steps involved in Cricket and Football. In the figure below template for cricket appears and it contains the same order as order described in abstract class.
  • 22.
    22 Fig. 3.8.1 templatefor cricket Steps involve for playing football is similar to cricket so we can use same abstract class for football also. Following screenshot explains similarity between both the templates. Fig. 3.8.2 template for football and cricket 3.9 Chain Responsibility Design pattern Chain responsibility design pattern gives opportunity to object to handle request. Actually what happen, sender sends request to the chain of objects , and each object handle specific request , chain responsibility gives to multiple objects a opportunity to handle request. Like Gmail account different Handlers to handle specific type of email that handle primary messages ,social messages, forum messages in a chain.
  • 23.
    23 Another example isto handle different numbers like positive, negative and zero numbers. Fig. 3.7.1 Chain Responsibility Design pattern example To handle positive, negative and zero numbers there is three buttons first button to handle negative number, second button to handle positive number and zero number handled by third button . JLabel is used to show messages. User sends request through TextField and if number is greater than zero then it will send request to each handler to handle request. So, value is suppose 10 then it will handle by positive handler button , and if value is suppose -10 then it will handle by negative handler button and zero number by zero handler button. If we try to handle -10 by positive handler button then handler will discard to requests and it will show message Negative Number will Not handled by this positive handler button. We can use this application in shopping cart where customer requests for any item and this request handled by specific handler 3.8 Mediator design pattern When to object trying to communicate with each other some times it become more complex , and complexity may be because of structure of object or type of object .So, mediator design pattern provides loose coupling between objects to reduce complexity among multiple objects or classes ,So it provides a class which normally handle all communication between different classes or different objects. For example suppose there is a class to handle messages , users send messages to this class and it’s responsibility of this class to show this messages to all users so, there is a class to handle user objects and another class uses this objects to show communication between them.
  • 24.
    24 Fig. 3.8.1 Mediatordesign pattern example First of all one user will register his name to communicate with another user and through given text field and send message to the class which handle this messages, will show his messages then another user will register his name and then sends his messages and class will show this messages to another users. 3.9 Strategy DesignPattern In strategy pattern , a class behavior or algorithm can change at run time. In strategy pattern we create object which represent various strategy. Strategy pattern can encapsulate various algorithms in a one class to change algorithm at run time . For example a file compressor ,there is a compressor strategy class which select different algorithms at run time to compress files. Fig. 3.9.1 Strategy Design Pattern example 1
  • 25.
    25 This compressor strategyclass handle multiple algorithms and can execute one of them at run time. Compressor button is used to handle class which handle multiple algorithms and at run time can execute either zip, gzip or may be rar to compress file. Another feature is it can change behavior of class at run time. For example a class context which change it’s behavior at run time , by either executes addition operation or subtraction or multiplication of numbers. Fig. 3.9.2 Strategy Design Pattern example 2 There is three TextFieds to handle inputs and outputs and three operations will given here which will change by strategy class at run time. So it maintain complexity of software. When we build a large software ,software developer care about complexity and execution time of algorithms so in this case it’s beneficial to use strategy design pattern in place using large set of switch cases to execute different strategies at run time, Because software developer always trying to prohibit to use switch cases and always trying to eliminate more execution time. So it’s better to use strategy pattern for this purpose by encapsulates multiples algorithms or change execution at run time. 3.10 Iterator DesignPattern When a software developer develop large application and there is a problem creates related with accessing date from large collections of data, then it is beneficial to use Iterator design pattern, in terms of to access a data from large collection, it accesses data from collection with out exposing data structure of elements . For example, channel collections of hindi , English ,French with different frequencies are decoupled because of iterator design pattern. How ever this pattern also used for classification of attributes, for example in this GUI which is given below for hindi
  • 26.
    26 channel it separatesit by frequency also to English, French channel classified by frequency. Fig. 3.10.1 Iterator Design Pattern example There is three buttons for English channel, hindi channel, French channel and when we click one of them ,suppose English button then it sends request to handler to classify each English channel by frequency from another channels and show Dialog- box used to show messages, and same kind of stuff we do for hindi channel, French channel. However this property can used in classification of attributes like apriori in data mining, Iterator design pattern search for english channel along with frequency, and classify all channels according to the frequency. 3.11 Interpreter Design Pattern Iterator design pattern is used to map a value to a given expression or a grammar expression may be complex ,like postfix notation and infix expression in data structure, this pattern used to evaluate it’s value. Interpreter design pattern map a domain to a language,the language to a grammar a grammar to a object oriented design. Defining a language as a simple language grammar, representing domain rules as a language sentence, and interpreting these sentence to solve the problem. Pattern uses a class to represent each grammar rule. for example suppose there is an digits in roman, by intepreter design pattern it will interpret in to English digits. It interpret complex expression or grammar in to single value. It's GUI representation is given below:-
  • 27.
    27 Fig. 3.11.1 parserfrom roman to English digit This GUI uses a button to parse given roman number into digits, so it content a text field through user gives input and when clicking at parse button it assign digit. Context class handles input and expression abstract class handle expression. Class handle objects to request to evaluate expressions value. 3.12 Observer DesignPattern One famous example we know of observer design pattern publisher/subscriber which hold one-to-many relationship between objects, JMS (java message services) and socket programming is way to implement this relation, it maintain publisher/subscriber servers to publish and subscribes messages. However Observer design pattern is used to implement one-to-many relation between objects, such as if one object is modified ,its dependent objects are to be notify automatically for example:-suppose subject and concrete class object to show observer pattern in action- Fig 3.12.1 observer design pattern example In this example there is three observers hexadecimal, octal, binary and suppose in first time state change occurs when input given suppose 234 then hexadecimal will observe EA, Octal observer will observe 352 and Binary observer will observe
  • 28.
    28 11101010, in sameway when user provides different input, observer will observe different output as explain in above line.
  • 29.
    29 4. TUTORIAL We havedeveloped a tutorial in php for design pattern and all the applications mentioned above are attached to the tutorial so that it can be easy for the user to understand each and every design pattern properly. Code for each attached application is linked along with that application a link is given below the application from where it can be viewed. A video is attached at the home page which can explain the functionality and use of the tutorial. Below is the screen shot of the home page : Fig. 4.1 home page of tutorial Home page contains basic definition of design pattern and link to further pages are given at this page for further study. Video at this page explains functionality and basic use of this tutorial.
  • 30.
    30 Fig. 4.2 Introductionpage of tutorial Now each design pattern is explained individually and its application is attached to it. Below is the screen shot of the tutorial that contains attached singleton pattern.
  • 31.
    31 Fig. 4.3 Singletonpattern in tutorial
  • 32.
    32 5. CONCLUSION ANDSCOPE After analyzing and studying each design pattern we came to know that knowledge of design pattern is necessary if we want to develop a software with tightly coupled classes, modular and readable code. The key is to learn to identify the scenarios and problems in software development which the patterns are meant to address. Often we face problems during software development in which no combination of design patterns can be used to solve that problem. At that point more attention needs to be given to the problem rather than the solution. So we came to the conclusion that each and every design pattern if studied properly can be advantageous at many places in software development where we stuck at some situation and unable to come out of that because of lack of ideas to solve that problem. Sometimes it may feel that design pattern increase complexity of code and software and sometimes it is true. Because problems of smaller applications have several solutions which are easier to implement and less complex than design pattern but if we are developing a complex software with many lines of code then it very impractical to start coding randomly and often we end up in the middle of nowhere and our code becomes so unreadable . Main scope of studying design pattern is in software development and with a collaborative study we learn to take advantages of object oriented programming language in terms of design pattern. We learn to understand problems and its solution. For example suppose developer A has developed a vlc media player application but if user clicks on the icon twice by mistake then it opens two window of vlc media player. Obviously it is impractical to watch something in two windows and user has to close one of them manually. So developer would like to enhance this application adding a feature in which multiple clicks on the icon opens only a single window of vlc media player. But he has no idea how to add this functionality to an existing software and here comes the use of singleton design pattern. Adding a singleton class to his media player can ensure that only one instance of that media player can be created irrespective of the request for multiple instances.
  • 33.
    33 REFERENCES Books [1]Design Pattern: Elementsof Reusable object-oriented Software By :Erich Gamma, Richard Helm ,Ralph Johnson, John M.Vlissides (GOF) [2]Head First design Patterns, By: Elisabeth Freeman, Eric Freeman, BertBates, Kathy Sierra [3]Pattern Hatching: Design Patterns Applied By: John M.Vlissides [4]Refactoring to Patterns, By: Joshua Kerievsky [5]Patterns of Enterprise Application Architecture By:Martin Fowler Journals [1]Douglas A.Lyon and Francisco castellanos “The parametric singleton design pattern”, in journal of object technology, March- April 2007 http://www.jot.fm/issues/issue_2007_03/column2 Thesis [1]The “Gang Of Four” Pattern Implemented in java, Mater’s Thesis [2]Object Oriented Design Pattern, By Marcel Birkner