Top Banner
Design Patterns Mohan Bang Email: [email protected]
47
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Design Patterns

Design Patterns

Mohan BangEmail: [email protected]

Page 2: Design Patterns

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 …

Page 3: Design Patterns

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 }

StructuredExceptionHandling

Page 4: Design Patterns

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

Page 5: Design Patterns

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)

Page 6: Design Patterns

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.

Page 7: Design Patterns

The Gang of Four (GOF) Erich Gamma, Richard Helm, Ralph

Johnson, and John Vlissides "Design Patterns: Elements of

Reusable Object-Oriented Software" (1995)

Page 8: Design Patterns
Page 9: Design Patterns

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.

Page 10: Design Patterns

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

Page 11: Design Patterns

Design Patterns

1) 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.

Page 12: Design Patterns

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 extendsShapeFactory 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 objectsshape = new Square();}else throw new BadShapeException(“ShapeTypeId=”+ shapeTypeId);return shape;}}Now let’s look at the calling code, which uses thefactory: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

Page 13: Design Patterns

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.

Page 14: Design Patterns

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

Page 15: Design Patterns

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.

Page 16: Design Patterns

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 PatternSingleton 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.

DisadvantageSingleton Pattern Object, HashMap & ArrayList are responsible for Memory Leaks.

Page 17: Design Patterns

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).

Page 18: Design Patterns

Proxy Pattern –

To provide a placeholder for another object to control access to it.

Page 19: Design Patterns

Example of Proxy Pattern

// Operations.javapackage proxies;

public interface Operations {public int add(int a, int b);public int sub(int a, int b);

}

Page 20: Design Patterns

Example of Proxy Pattern Contd..

// BusinessLogic.javapackage 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;}

}

Page 21: Design Patterns

Example of Proxy Pattern Contd..

// BusinessProxy.javapackage 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;}

}

Page 22: Design Patterns

Example of Proxy Pattern Contd..

// BusinessFactory.javapackage proxies;

public class BusinessFactory {public static Operations getObject(){

return new BusinessProxy();}

}

Page 23: Design Patterns

Example of Proxy Pattern Contd..

// BusinessClient.javapackage proxies;

public class BusinessClient {public static void main(String[] args) {

Operations o = BusinessFactory.getObject();int res = o.sub(20,20);System.out.println(res);

}}

Page 24: Design Patterns

How Design Patterns will help us in creating Architecture?

Page 25: Design Patterns

Our Problem –

How to make loose coupling between business and persistence logic?

Options - a) Adapter Patternb) DAO Patternc) Business Delegated) Factory Pattern

Page 26: Design Patterns

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

Page 27: Design Patterns

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.

Page 28: Design Patterns

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.

Page 29: Design Patterns

Our Problem –

How can an intermediary class can be created to make loosely couple client and business tier?

Options - a) Adapter Patternb) Business Delegatec) Factory Patternd) MVC Pattern

Page 30: Design Patterns

Solution –

Create a layer of business delegates. Plain Java classes that hide the complexity

by encapsulating code required to discover.

Page 31: Design Patterns

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)

Page 32: Design Patterns

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

Page 33: Design Patterns

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 -

Page 34: Design Patterns

The main purpose of using MVC pattern is to decouple the GUI from the Data. It alsogives the ability to provide multiple views for the same Data. MVC pattern separatesobjects 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. Viewis 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 -

Page 35: Design Patterns

MVC Architecture -

Page 36: Design Patterns

Flow of a Struts Application

Page 37: Design Patterns

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

Page 38: Design Patterns

Problem: In the model 1 architecture the JSP page is alone responsible for processing the incoming request andreplying back to the user. This architecture may be suitable for simple applications, but complex applications willend up with significant amount of Java code embedded within your JSP page, especially when there is significantamount of data processing to be performed. This is a problem not only for java developers due to design uglinessbut also a problem for web designers when you have large amount of Java code in your JSP pages. In manycases, the page receiving the request is not the page, which renders the response as an HTML output becausedecisions 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 amessy flow of control and design ugliness for the application. So, why should you use a JSP page as acontroller, 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 hybridapproach for serving dynamic content, since it combines the use of both Servlets and JSPs. It takes advantage ofthe predominant strengths of both technologies where a Servlet is the target for submitting a request andperforming 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 orobjects used by the JSP as well as deciding, which JSP page to forward or redirect the request to (i.e. flowcontrol) depending on the data submitted by the user. The JSP page is responsible for retrieving any objects orbeans that may have been previously created by the servlet, and as a template for rendering the view as aresponse 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 thebusiness logic model (e.g. EJB, POJO - Plain Old Java Object, JavaBeans etc). Then select the next JSP view fordisplay and deliver the view to client as the presentation (response). It is the best practice to use Web tier UIframeworks like Struts, JavaServer Faces etc, which uses proven and tested design patterns.

MVC – I and MVC - II Pattern

Page 39: Design Patterns

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

Page 40: Design Patterns

Framework based on MVC Design Pattern

Struts Framework Webwork Framework TCF (Thin Client Framework) Spring Framework

Page 41: Design Patterns

Intercepting Filter Pattern:Intercepting Filter Pattern:

Pre- and post-process application requestsPre- 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}

Page 42: Design Patterns

These design pattern 'adapts' one interface for a class into one that a These design pattern 'adapts' one interface for a class into one that a client expects. An adapter allows classes to work together that normally client expects. An adapter allows classes to work together that normally could not because of incompatible interfaces by wrapping its own could not because of incompatible interfaces by wrapping its own interface around that of an already existing class. The adapter is also interface around that of an already existing class. The adapter is also responsible for handling any logic necessary to transform data into a responsible for handling any logic necessary to transform data into a form that is useful for the consumer. For instance, if multiple boolean form that is useful for the consumer. For instance, if multiple boolean values are stored as a single integer but your consumer requires a values are stored as a single integer but your consumer requires a 'true'/'false', the adapter would be responsible for extracting the 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value. appropriate values from the integer value. It is also called as Wrapper It is also called as Wrapper PatternPattern..We can use this pattern to get contents from Servers through web We can use this pattern to get contents from Servers through web services.services.

Adapter Pattern

Page 43: Design Patterns

Scenario

Outlets and PlugsOutlets 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.

Page 44: Design Patterns

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.

Page 45: Design Patterns
Page 46: Design Patterns

Intercepting Filter: Pre- and post-process application requests

Struts MVC / Action: Decouple data representation, application behavior, and presentation

Business Delegate: Reduce coupling between Web and Enterprise JavaBeansTM tiers

Data Access Object: Abstract and encapsulate data access mechanisms

View Helper: Simplify access to model state and data access logic

Factory: 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.

Singleton: Ensure a class has only one instance, and provide a global point of access to it. Class Name: CSingleton & field member: private static CSingleton instance = null; If I require a single instance of an object in a particular JVM, like for example while designing database connection pool. I would require a single connection object for all the users coming in, not a separate one for each user.

Adapter / Decorator / Wrapper: 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.

Page 47: Design Patterns

Thanks