Design Patterns In Java Tutorial - Jad Matta

1y ago
5 Views
1 Downloads
2.39 MB
168 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Kaden Thurman
Transcription

Design Patterns in Java Tutorial

DESIGN PATTERNS IN JAVA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i

ABOUT THE TUTORIAL Design Patterns in Java Tutorial Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. This tutorial will take you through step by step approach and examples using Java while learning Design Pattern concepts. Audience This reference has been prepared for the experienced developers to provide best solutions to certain problems faced during software development and for un-experienced developers to learn software design in an easy and faster way. Prerequisites Before proceeding with this tutorial you should have a good understanding of Java programming language. A basic understanding of Eclipse IDE is also required because all the examples have been compiled using Eclipse IDE. Copyright & Disclaimer Notice All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com ii

Table of Contents Design Patterns in Java Tutorial. i Audience . i Prerequisites . i Copyright & Disclaimer Notice . i Design Pattern Overview . 1 Common platform for developers . 1 Best Practices . 2 Factory Pattern . 3 Implementation . 3 Class Diagram . 3 Steps . 4 Abstract Factory Pattern . 7 Implementation . 7 Class Diagram . 8 Steps . 9 Singleton Design Pattern . 14 Implementation . 14 Class Diagram . 15 Steps . 16 Builder Design Pattern. 18 Implementation . 18 Class Diagram . 19 Steps . 19 Prototype Design Pattern . 24 Implementation . 24 Class Diagram. . 25 Steps . 26 Adapter Design Pattern. 29 Implementation . 29 Class Diagram . 30 Steps . 31 Bridge Design Pattern . 34 iii

Implementation . 34 Class Diagram . 35 Steps . 36 Filter Design Pattern. 38 Implementation . 38 Class Diagram . 39 Steps . 40 Composite Design Pattern . 45 Implementation . 45 Class Diagram . 46 Steps . 47 Decorator Design Pattern . 49 Implementation . 49 Class Diagram . 50 Steps . 51 Façade Design Pattern . 54 Implementation . 54 Class Diagram . 55 Steps . 56 Flyweight Design Pattern . 58 Implementation . 58 Class Diagram . 59 Steps . 60 Proxy Design Pattern . 63 Implementation . 63 Class Diagram . 64 Steps . 65 Chain of Responsibility Design Pattern . 67 Implementation . 67 Class Diagram . 68 Steps . 69 Command Design Pattern . 72 Implementation . 72 Class Diagram . 73 Steps . 74 Interpreter Design Pattern . 77 Implementation . 77 Class Diagram . 78 iii

Steps . 79 Iterator Design Pattern . 82 Implementation . 82 Class Diagram . 83 Steps . 84 Mediator Design Pattern . 86 Implementation . 86 Class Diagram . 87 Steps . 88 Memento Design Pattern. 90 Implementation . 90 Class Diagram . 91 Steps . 92 Observer Design Pattern . 94 Implementation . 94 Class Diagram . 95 Steps . 96 State Design Pattern . 99 Implementation . 99 Class Diagram . 100 Steps . 101 Null Object Design Pattern . 103 Implementation . 103 Class Diagram . 104 Steps . 105 Strategy Design Pattern . 108 Implementation . 108 Class Diagram . 109 Steps . 110 Template Design Pattern . 112 Implementation . 112 Class Diagram . 113 Steps . 114 Visitor Design Pattern . 116 Implementation . 116 Class Diagram . 117 Steps . 118 MVC Design Pattern . 121 iii

Implementation . 121 Class Diagram . 122 Steps . 123 Business Delegate Design Pattern . 126 Implementation . 126 Class Diagram . 127 Steps . 128 Composite Entity Design Pattern . 131 Implementation . 131 Class Diagram . 132 Steps . 133 Data Access Object Design Pattern . 136 Implementation . 136 Class Diagram . 137 Steps . 138 Front Controller Design Pattern . 141 Implementation . 141 Class Diagram . 142 Steps . 143 Intercepting Filter Design Pattern . 145 Implementation . 145 Class Diagram . 146 Steps . 147 Service Locator Design Pattern. 150 Implementation . 150 Class Diagram . 151 Steps . 152 Transfer Object Design Pattern . 156 Implementation . 156 Class Diagram . 157 Steps . 158 About tutorialspoint.com . 161 iii

1 CHAPTER Design Pattern Overview This chapter gives a basic idea about Design Patterns starting with their origin, their evaluation over time and their classifications. D esign patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time. Gang of Four (GOF) In 1994, four authors Erich Gamma, Richard Helm; Ralph Johnson und John Vlissides published a book titled Design Patterns - Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development. These authors are collectively known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design. Program to an interface not an implementation Favor object composition over inheritance Usage of Design Pattern Design Patterns have two main usages in software development. Common platform for developers Design patterns provide a standard terminology and are specific to particular scenario. For example, a singleton design pattern signifies use of single object so all developers familiar with TUTORIALS POINT Simply Easy Learning Page 1

single design pattern will make use of single object and they can tell each other that program is following a singleton pattern. Best Practices Design patterns have been evolved over a long period of time and they provide best solutions to certain problems faced during software development. Learning these patterns helps unexperienced developers to learn software design in an easy and faster way. Types of Design Pattern As per the design pattern reference book Design Patterns - Elements of Reusable ObjectOriented Software, there are 23 design patterns. These patterns can be classified in three categories: Creational, Structural and behavioral patterns. We'll also discuss another category of design patterns: J2EE design patterns. S.N. Pattern & Description 1 Creational Patterns 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. 2 Structural Patterns 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. 3 Behavioral Patterns These design patterns are specifically concerned with communication between objects. 4 J2EE Patterns These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java Center. TUTORIALS POINT Simply Easy Learning Page 2

2 CHAPTER Factory Pattern This section describes factory pattern and its implementation. F actory pattern is one of most used design pattern in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. Implementation We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step. FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs. Class Diagram TUTORIALS POINT Simply Easy Learning Page 3

Steps Use the following steps to implement the above mentioned design pattern. Step 1 Create an interface. Shape.java public interface Shape { void draw(); } Step 2 Create concrete classes implementing the same interface. Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } TUTORIALS POINT Simply Easy Learning Page 4

Step 3 Create a Factory to generate object of concrete class based on given information. ShapeFactory.java public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape(String shapeType){ if(shapeType null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } } Step 4 Use the Factory to get object of concrete class by passing an information such as type. FactoryPatternDemo.java public class FactoryPatternDemo { public static void main(String[] args) { ShapeFactory shapeFactory new ShapeFactory(); //get an object of Circle and call its draw method. Shape shape1 shapeFactory.getShape("CIRCLE"); //call draw method of Circle shape1.draw(); //get an object of Rectangle and call its draw method. Shape shape2 shapeFactory.getShape("RECTANGLE"); //call draw method of Rectangle shape2.draw(); //get an object of Square and call its draw method. Shape shape3 shapeFactory.getShape("SQUARE"); //call draw method of circle shape3.draw(); } } TUTORIALS POINT Simply Easy Learning Page 5

Step 5 Verify the output. Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method. TUTORIALS POINT Simply Easy Learning Page 6

3 CHAPTER Abstract Factory Pattern This section describes abstract factory pattern and its implementation. A bstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern. Implementation We're going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We creates an abstract factory class AbstractFactory as next step. Factory classesShapeFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created. AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs. It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs. TUTORIALS POINT Simply Easy Learning Page 7

Class Diagram TUTORIALS POINT Simply Easy Learning Page 8

Steps Use the following steps to implement the above mentioned design pattern. Step 1 Create an interface for Shapes. Shape.java public interface Shape { void draw(); } Step 2 Create concrete classes implementing the same interface. Rectangle.java public class Rectangle implements Shape { @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } Square.java public class Square implements Shape { @Override public void draw() { System.out.println("Inside Square::draw() method."); } } Circle.java public class Circle implements Shape { @Override public void draw() { System.out.println("Inside Circle::draw() method."); } } Step 3 Create an interface for Colors. TUTORIALS POINT Simply Easy Learning Page 9

Color.java public interface Color { void fill(); } Step4 Create concrete classes implementing the same interface. Red.java public class Red implements Color { @Override public void fill() { System.out.println("Inside Red::fill() method."); } } Green.java public class Green implements Color { @Override public void fill() { System.out.println("Inside Green::fill() method."); } } Blue.java public class Blue implements Color { @Override public void fill() { System.out.println("Inside Blue::fill() method."); } } Step 5 Create an Abstract class to get factories for Color and Shape Objects. AbstractFactory.java public abstract class AbstractFactory { abstract Color getColor(String color); abstract Shape getShape(String shape) ; } TUTORIALS POINT Simply Easy Learning Page 10

Step 6 Create Factory classes extending AbstractFactory to generate object of concrete class based on given information. ShapeFactory.java public class ShapeFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ if(shapeType null){ return null; } if(shapeType.equalsIgnoreCase("CIRCLE")){ return new Circle(); } else if(shapeType.equalsIgnoreCase("RECTANGLE")){ return new Rectangle(); } else if(shapeType.equalsIgnoreCase("SQUARE")){ return new Square(); } return null; } @Override Color getColor(String color) { return null; } } ColorFactory.java public class ColorFactory extends AbstractFactory { @Override public Shape getShape(String shapeType){ return null; } @Override Color getColor(String color) { if(color null){ return null; } if(color.equalsIgnoreCase("RED")){ return new Red(); } else if(color.equalsIgnoreCase("GREEN")){ return new Green(); } else if(color.equalsIgnoreCase("BLUE")){ return new Blue(); } return null; } } TUTORIALS POINT Simply Easy Learning Page 11

Step 7 Create a Factory generator/producer class to get factories by passing an information such as Shape or Color FactoryProducer.java public class FactoryProducer { public static AbstractFactory getFactory(String choice){ if(choice.equalsIgnoreCase("SHAPE")){ return new ShapeFactory(); } else if(choice.equalsIgnoreCase("COLOR")){ return new ColorFactory(); } return null; } } Step 8 Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing information such as type. AbstractFactoryPatternDemo.java public class AbstractFactoryPatternDemo { public static void main(String[] args) { //get shape factory AbstractFactory shapeFactory FactoryProducer.getFactory("SHAPE"); //get an object of Shape Circle Shape shape1 shapeFactory.getShape("CIRCLE"); //call draw method of Shape Circle shape1.draw(); //get an object of Shape Rectangle Shape shape2 shapeFactory.getShape("RECTANGLE"); //call draw method of Shape Rectangle shape2.draw(); //get an object of Shape Square Shape shape3 shapeFactory.getShape("SQUARE"); //call draw method of Shape Square shape3.draw(); //get color factory AbstractFactory colorFactory FactoryProducer.getFactory("COLOR"); TUTORIALS POINT Simply Easy Learning Page 12

//get an object of Color Red Color color1 colorFactory.getColor("RED"); //call fill method of Red color1.fill(); //get an object of Color Green Color color2 colorFactory.getColor("Green"); //call fill method of Green color2.fill(); //get an object of Color Blue Color color3 colorFactory.getColor("BLUE"); //call fill method of Color Blue color3.fill(); } } Step 9 Verify the output. Inside Circle::draw() method. Inside Rectangle::draw() method. Inside Square::draw() method. Inside Red::fill() method. Inside Green::fill() method. Inside Blue::fill() method. TUTORIALS POINT Simply Easy Learning Page 13

4 CHAPTER Singleton Design Pattern This section describes singleton pattern and its implementation. S ingleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object. This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class. Implementation We're going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself. SingleObject class provides world.SingletonPatternDemo, a SingleObject object. TUTORIALS POINT Simply Easy Learning a static method to get our demo class will its static instance to outside use SingleObject class to get Page 14

Class Diagram TUTORIALS POINT Simply Easy Learning Page 15

Steps Use the following steps to implement the above mentioned design pattern. Step 1 Create a Singleton Class. SingleObject.java public class SingleObject { //create an object of SingleObject private static SingleObject instance new SingleObject(); //make the constructor private so that this class cannot be //instantiated private SingleObject(){} //Get the only object available public static SingleObject getInstance(){ return instance; } public void showMessage(){ System.out.println("Hello World!"); } } Step 2 Get the only object from the singleton class. SingletonPatternDemo.java public class SingletonPatternDemo { public static void main(String[] args) { //illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object new SingleObject(); //Get the only object available SingleObject object SingleObject.getInstance(); //show the message object.showMessage(); } } TUTORIALS POINT Simply Easy Learning Page 16

Step 3 Verify the output. Hello World! TUTORIALS POINT Simply Easy Learning Page 17

5 CHA

design patterns: J2EE design patterns. S.N. Pattern & Description 1 Creational Patterns 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. 2

Related Documents:

java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.

Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears:

Java Tutorial Java Tutorial or Core Java Tutorial or Java Programming Tutorial is a widely . An application that runs on the server side and creates dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java. 2/20/17 09:58:44 AM 11 .

3. _ is a software that interprets Java bytecode. a. Java virtual machine b. Java compiler c. Java debugger d. Java API 4. Which of the following is true? a. Java uses only interpreter b. Java uses only compiler. c. Java uses both interpreter and compiler. d. None of the above. 5. A Java file with

JAVA TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com. TUTORIALS POINT Simply Easy Learning ABOUT THE TUTORIAL Java Tutorial Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

besteht aus der Java-API (Java Application Programming Interface) und der Java-VM (Java Virtual Machine). Abbildung 1: Java-Plattform Die Java-API ist eine große Sammlung von Java-Programmen, die in sog. Pakete (packages) aufgeteilt sind. Pakete sind vergleichbar mit Bibliotheken in anderen Programmiersprachen und umfassen u.a.

JAR Javadoc Java Language jar Security Others Toolkits: FX Java 2D Sound . Java Programming -Week 1. 6/25. Outline Java is. Let’s get started! The JDK The Java Sandbox . into your namespace. java.lang contains the most basic classes in the Java language. It is imported automatically, so

2 Java Applications on Oracle Database 2.1 Database Sessions Imposed on Java Applications 2-1 2.2 Execution Control of Java Applications 2-3 2.3 Java Code, Binaries, and Resources Storage 2-3 2.4 About Java Classes Loaded in the Database 2-4 2.5 Preparing Java Class Methods for Execution 2-5 2.5.1 Compiling Java Classes 2-6