Design Patterns

Uploaded on

Design Patterns

Design Patterns

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. Design Patterns Mohan Bang Email:
  • 2. Agenda
    • What are Design Patterns?
    • How Design Pattern begins?
    • Why do we need Design Patterns?
    • How many Design Patterns?
    • What is the relationship among these Patterns?
    • Overview on Design Patterns in Architecture
    • Conclusion and Summary
    In this presentation, we’ll discuss about …
  • 3. You Use Patterns Every Day...
    • try
    • { something }
    • catch (SqlException qx)
    • { handle SQL error }
    • catch (SecurityException sx)
    • { handle security violation }
    • catch (Exception ex)
    • { handle all other exceptions }
    • finally
    • { clean up resources }
    Structured Exception Handling
  • 4. What are Design Patterns?
    • Design Pattern - The design patterns are language-independent strategies for solving common object-oriented design problems.
    • Informal Design Patterns
      • Code constructs, best practice, well-structured, common sense, the accepted approach, evolved over time
    • Formal Design Patterns
      • Documented as "Context", "Problem", "Solution", and a UML diagram
      • Have specific aims
      • Solve specific issues
  • 5. How Design Pattern begins?
    • If a problem occurs over and over again (recurring problems), a solution to that problem has been used effectively. That solution is described as a pattern.
    • When you make a design, you should know the names of some common solutions. In fact, you may have been familiar with some design patterns, you may not use well-known names to describe them.
    • GOF (Gang of four - Four pioneer guys who wrote a book named "Design Patterns"- Elements of Reusable Object-Oriented Software)
  • 6. Why do we need Design Patterns?
    • Why Design Patterns?
    • Expert designers know not to solve every problem from first principles.
    • They reuse solutions.
    • These patterns make OO designs more flexible, elegant, and ultimately reusable.
    • Best practice solution to commonly recurring problems.
    • Enable us to design efficient, scalable and maintainable systems.
    • What are the benefits of Design Patterns?
    • Provides a high-level language to discuss design issues.
    • Provides much of the design.
    • Combinations of patterns form reusable architectures.
  • 7. The Gang of Four (GOF)
    • Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
    • "Design Patterns: Elements of Reusable Object-Oriented Software" (1995)
  • 8. Based on Design Patterns
  • 9. How many design patterns?
    • Many. A site says 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.
    • Note that the design patterns are not algorithms or components.
    • Patterns are discovered, not created.
  • 10. What is the relationship among these patterns?
    • Generally, to build a system, you may need many patterns to fit together. Different designer may use different patterns to solve the same problem.
    • Usually:
      • Some patterns naturally fit together
      • One pattern may lead to another
      • Some patterns are similar and alternative
      • Patterns are discoverable and documentable
      • Patterns are not methods or framework
      • Patterns give you hint to solve a problem effectively
  • 11. Design Patterns
    • Creational Pattern
    • Factory Pattern -
    • It is used in place where the implementation varies over time. Factory pattern suggest to create many different instances from interfaces. Interfaces are the one that faces client and implementation of those methods come from factory depending on a specific condition. An example: If the OS is Windows, look and feel of the application changes to Window style, for Linux it is Metal and for Macintosh it will be different.
    • In short they hide the complexity of creating objects.
  • 12. Example of Factory Pattern
    • public interface Const {
    • public static final int SHAPE_CIRCLE =1;
    • public static final int SHAPE_SQUARE =2;
    • public static final int SHAPE_HEXAGON =3;
    • }
    • public class ShapeFactory {
    • public abstract Shape getShape(int shapeId);
    • }
    • public class SimpleShapeFactory extends
    • ShapeFactory throws BadShapeException {
    • public Shape getShape(int shapeTypeId){
    • Shape shape = null;
    • if(shapeTypeId == Const.SHAPE_CIRCLE) {
    • //in future can reuse or cache objects.
    • shape = new Circle();
    • }
    • else if(shapeTypeId == Const.SHAPE_SQUARE) {
    • //in future can reuse or cache objects
    • shape = new Square();
    • }
    • else throw new BadShapeException
    • (“ShapeTypeId=”+ shapeTypeId);
    • return shape;
    • }
    • }
    • Now let’s look at the calling code, which uses the
    • factory:
    • ShapeFactory factory = new SimpleShapeFactory();
    • //returns a Shape but whether it is a Circle or a
    • //Square is not known to the caller.
    • Shape s = factory.getShape(1);
    • s.draw(); // circle is drawn
    • //returns a Shape but whether it is a Circle or a
    • //Square is not known to the caller.
    • s = factory.getShape(2);
    • s.draw(); //Square is drawn
  • 13. Singleton Pattern – Ensure a class has only one instance, and provide a global point of access to it. If I require a single instance of an object in a particular JVM, like for example while creating log file. I would require a single object for all the users coming in, not a separate one for each user. A DataSource should have only a single instance where it will supply multiple connections from its single DataSource pool. A singleton class used only to keep, load, save the state of configuration.
  • 14. Singleton Pattern
    • Provides for creation of a class for which only a single instance can exist
    • Useful for exposing read-only data
    • Useful for exposing static methods that do not rely on instance data
    • Include private default constructor to prevent client initialization
    • Provide a static getInstance() method (unsynchronized ‘lazy’ method) that returns the current instance
  • 15. How can we implement singleton pattern? There are many instances in a project where you will need only one instance to be running. This one instance can be shared across objects. For instance you will only want one instance of database connection object running. Singleton pattern assures that only one instance of the object is running through out the applications life time. Below is the code snippet which shows how we can implement singleton pattern. public class OnlyOne { private static OnlyOne one = new OnlyOne(); private OnlyOne() { … //private constructor. This class cannot be instantiated from outside. } public static OnlyOne getInstance() { return one; } } To use it: //No matter how many times you call, you get the same instance of the object. OnlyOne myOne = OnlyOne.getInstance(); There are two important steps to be done in order to achieve the same:- √ Define the constructor as private. That means any external client can not create object of the same. √ Second define the object as static which needs to be exposed by the singleton pattern so that only one instance of the object is running.
  • 16.
    • When to use Static Class and when to use the Singleton Pattern
    • The singleton pattern is useful when the object itself needs to keep some state. If no such thing is needed, a static method can do the job as well. A purely static class can save state as well.
    • A static variable can be used to store state. A static block can be used initialize state. A static method can be used to access or modify the state. But, the static method can affect security.
    • A purely static class cannot do is to force parameterization of the initialization of the class, since any method call can trigger the static initialization block. Such forced parameterization can be provided in the singleton by only providing an .instance () method with the desired arguments in the parameter list.
    • A class full of static methods can't be polymorphic, but a singleton can. So if you want to decide at runtime which implementation of this thing you are to going to use, you have to go with the singleton.
    • A singleton will require less effort, having extra option of initializing the class and more flexible as compare to static class. It is used only to keep, load, save the state of configuration.
    • A singleton can extend classes and implement interfaces, while a static class cannot (well, it can extend classes, but it does not inherit their instance members).
    • A singleton can be initialized lazily (unsynchronized getInstance() method) while a static class is generally initialized when it is first loaded.
    • When to use the Singleton Pattern
    • Singleton Pattern is at its best when it provides following benefits:
    • It hides the instance initialization
    • It allows lazy initialization (unsynchronized getInstance() method).
    • It ensures single instance of an object and can control the number of instances, which is one of the important feature.
    • Disadvantage
    • Singleton Pattern Object, HashMap & ArrayList are responsible for Memory Leaks.
  • 17. 2) Structural Pattern Session Façade Pattern – It increases the performance over the network.. In this case we call session bean (Bean holding data in Session) which on turn call entity bean (Bean holding data at server side).
  • 18. Proxy Pattern – To provide a placeholder for another object to control access to it.
  • 19. Example of Proxy Pattern
    • //
    • package proxies;
    • public interface Operations {
    • public int add(int a, int b);
    • public int sub(int a, int b);
    • }
  • 20. Example of Proxy Pattern Contd..
    • //
    • package proxies;
    • public class BusinessLogic implements Operations{
    • public int add(int a, int b)
    • {
    • return a+b;
    • }
    • public int sub(int a, int b)
    • {
    • return a-b;
    • }
    • }
  • 21. Example of Proxy Pattern Contd..
    • //
    • package proxies;
    • public class BusinessProxy implements Operations{
    • public int add(int a, int b) {
    • int res = 0;
    • if(a<100&&b>100)
    • {
    • BusinessLogic bl = new BusinessLogic();
    • res = bl.add(a,b);
    • return res;
    • }
    • return res;
    • }
    • public int sub(int a, int b) {
    • int res = 0;
    • BusinessLogic bl = new BusinessLogic();
    • res = bl.sub(a,b);
    • if(res==0)
    • {
    • try {
    • throw new Exception();
    • } catch (Exception e) {
    • e.printStackTrace();
    • System.exit(0);}
    • }return res;
    • }
    • }
  • 22. Example of Proxy Pattern Contd..
    • //
    • package proxies;
    • public class BusinessFactory {
    • public static Operations getObject()
    • {
    • return new BusinessProxy();
    • }
    • }
  • 23. Example of Proxy Pattern Contd..
    • //
    • package proxies;
    • public class BusinessClient {
    • public static void main(String[] args) {
    • Operations o = BusinessFactory.getObject();
    • int res = o.sub(20,20);
    • System.out.println(res);
    • }
    • }
  • 24. How Design Patterns will help us in creating Architecture?
  • 25.
    • Our Problem –
    • How to make loose coupling between business
    • and persistence logic?
    • Options -
      • Adapter Pattern
      • DAO Pattern
      • Business Delegate
      • Factory Pattern
  • 26.
    • What changes need to be made in code if we change the database schema? Does we require to make change in code?
    • Access to data varies depending on the source of the data. Access to persistent storage, such as to a database, varies greatly depending on the type of storage (relational databases, object-oriented databases, flat files, and so forth) and the vendor implementation.
    • Code that depends on specific features of data resources ties together business logic with data access logic. This makes it difficult to replace or modify an application's data resources.
    Data Access Object (DAO) Pattern
  • 27.
    • Solution –
    • Create a layer of data access objects.
    • Plain Java classes to make loose coupling between business and persistence logic.
    • No changes need to be made in code if we change the database schema. Also, we do not require to make change in code.
  • 28.
    • DAO Pattern –
    • Plain Java classes to make loose coupling between business and persistence logic
    • To execute SQL.
    • By changing the Data Layer / DAO, one can easily change the database also.
  • 29.
    • Our Problem –
    • How can an intermediary class can be created to
    • make loosely couple client and business tier?
    • Options -
      • Adapter Pattern
      • Business Delegate
      • Factory Pattern
      • MVC Pattern
  • 30.
    • Solution –
    • Create a layer of business delegates.
    • Plain Java classes that hide the complexity by encapsulating code required to discover.
  • 31. Business Delegate Pattern – It is an best practice to have an intermediate class to encapsulate access to a business service method. (Plain Java classes to loosely couple client and business tier)
  • 32. BusinessObject : requires access to the data source to obtain and store data. An Java object, a servlet or helper bean. DataAccessObject : abstracts the underlying data access implementation. Enables transparent access to the data source. DataSource : a database such as an RDBMS, OODBMS, XML repository, flat file system, another system (legacy/mainframe), service (B2B service or credit card bureau), or some kind of repository (LDAP). Common Participants in Architecture
  • 33. Struts is based on the MVC-II design pattern. Struts components can be categories into Model, View and Controller. Model : Components like business logic / business processes and data are the part of Model=> Application Object. View : JSP, HTML etc. are part of View.=>User Interface Controller : Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. (Decouple data representation, application behavior, and presentation)=>Defines the way the UI reacts to user inputs MVC Pattern -
  • 34. The main purpose of using MVC pattern is to decouple the GUI from the Data. It also gives the ability to provide multiple views for the same Data. MVC pattern separates objects into three important sections:- Model: - This section is specially for maintaining data. It is actually where your business logic, querying database, database connection etc. is actually implemented. Views: - Displaying all or some portion of data, or probably different view of data. View is responsible for look and feel, Sorting, formatting etc. Controller: - They are event handling section which affects either the model or the view. Controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display. MVC Pattern -
  • 35. MVC Architecture -
  • 36. Flow of a Struts Application
  • 37. MVC Pattern – Responsibilities
    • Model - the model represents enterprise data and the business rules that govern access to and updates of this data
    • View -the view renders the contents of a model. It accesses enterprise data through the model and specifies how that data should be presented
    • Controller - the controller translates interactions with the view into actions to be performed by the model
  • 38. Problem: In the model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the user. This architecture may be suitable for simple applications, but complex applications will end up with significant amount of Java code embedded within your JSP page, especially when there is significant amount of data processing to be performed. This is a problem not only for java developers due to design ugliness but also a problem for web designers when you have large amount of Java code in your JSP pages. In many cases, the page receiving the request is not the page, which renders the response as an HTML output because decisions need to be made based on the submitted data to determine the most appropriate page to be displayed. This would require your pages to be redirected (i.e. sendRedirect (…)) or forwarded to each other resulting in a messy flow of control and design ugliness for the application. So, why should you use a JSP page as a controller, which is mainly designed to be used as a template? Solution: You can use the Model 2 architecture (MVC – Model, View, Controller architecture), which is a hybrid approach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage of the predominant strengths of both technologies where a Servlet is the target for submitting a request and performing flow-control tasks and using JSPs to generate the presentation layer. As shown in the diagram below, the servlet acts as the controller and is responsible for request processing and the creation of any beans or objects used by the JSP as well as deciding, which JSP page to forward or redirect the request to (i.e. flow control) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects or beans that may have been previously created by the servlet, and as a template for rendering the view as a response to be sent to the user as an HTML. In the Model 2 MVC architecture, servlets process requests and select JSP views. So servlets act as controller. Servlets intercept the incoming HTTP requests from the client (browser) and then dispatch the request to the business logic model (e.g. EJB, POJO - Plain Old Java Object, JavaBeans etc). Then select the next JSP view for display and deliver the view to client as the presentation (response). It is the best practice to use Web tier UI frameworks like Struts, JavaServer Faces etc, which uses proven and tested design patterns. MVC – I and MVC - II Pattern
  • 39. MVC – I and MVC - II Pattern In model2, we have client tier as jsp, controller is servlet, and business logic is java bean. Controller and business logic beans are tightly coupled. And controller receives the UI tier parameters. But in MVC, Controller and business logic are loosely coupled and controller has nothing to do with the project/ business logic as such. Client tier parameters are automatically transmitted to the business logic bean , commonly called as ActionForm. So Model 2 is a project specific model and MVC is project independent. Example of MVC : Swing
  • 40. Framework based on MVC Design Pattern
    • Struts Framework
    • Webwork Framework
    • TCF (Thin Client Framework)
    • Spring Framework
  • 41. Intercepting Filter Pattern: Pre- and post-process application requests Entry in web.xml <filter> <filter-name>CFilter</filter-name> <filter-class>com.actions.CFilter</filter-class> </filter> <filter-mapping> <filter-name>CFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> public class CFilter extends implements Filter { // for validating user }
  • 42. These design pattern 'adapts' one interface for a class into one that a client expects. An adapter allows classes to work together that normally could not because of incompatible interfaces by wrapping its own interface around that of an already existing class. The adapter is also responsible for handling any logic necessary to transform data into a form that is useful for the consumer. For instance, if multiple boolean values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value. It is also called as Wrapper Pattern . We can use this pattern to get contents from Servers through web services. Adapter Pattern
  • 43. Scenario
    • Outlets and Plugs
    • Outlets in the US require a certain type of plug.
    • For example, a plug made in Europe for a European outlet, may not fit in an outlet in the US.
    • To use this appliance in the US, one would need to purchase an adapter.
  • 44. Overview on Adapter Pattern
    • Structural Patterns
    • Patterns that describe how we can form larger structures from classes or objects.
    • The Adapter Pattern is a structural pattern which can be a class or an object pattern.
    • Class patterns use inheritance to compose classes.
    • Object patterns use object composition .
  • 45. Thanks