Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
Now Reading
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Design patterns in Java, including design patterns in microservices, provide easily recognizable and usable object-oriented programming solutions to common problems.
The structure of a design pattern is well arranged into a template format to help the user quickly identify the problem and find its solution in reference to the relationship between the objects and the classes. It is a software template developers use to solve problems they encounter multiple times while designing a software application.
In this tutorial, you will learn about the various types of design patterns, the advantage of using design patterns, and when you should use design patterns. The tutorial will also cover the benefits of various design patterns and examples of the core Java design patterns.
The design patterns in software engineering are classified into the following three sub-categories:
Further classification of the design patterns is given in the table below:
Behavioral Design Pattern | Creational Design Pattern | Structural Design Pattern |
Template pattern | Abstract factory pattern | Bridge pattern |
Chain of responsibility pattern | Factory pattern | Adapter pattern |
Mediator pattern | Prototype pattern | Composite pattern |
Observer pattern | Singleton pattern | Decorator pattern |
Strategy pattern | Builder pattern | Flyweight pattern |
Command pattern | Object pool | Facade pattern |
State pattern | Proxy pattern | |
Visitor pattern | ||
Iterator pattern | ||
Interpretor pattern | ||
Memento pattern |
Behavioral design patterns give solutions based on object interaction. These design patterns recognize and understand common communication patterns among the objects.
Creational design patterns deal with how the objects are being created. Using creational design patterns, you can create objects and the classes associated with them with the least complexity in a controlled fashion. Creational pattern hides the instantiation process of an object and makes the system independent of how objects are composed, created, and represented.
Structural design pattern deals with the organization of the objects and the associated classes and how they are composed to make bigger structures. They are categorized into two categories: structural class patterns and structural object patterns.
There are several benefits of using design patterns. Some of these are as follows:
The following diagram gives an example of how we change a high cohesion code to low cohesion source code:
We should use Design Patterns in the following cases:
We have already covered the objectives of three types of Design Patterns at the beginning of this tutorial. Let us now look at the different types of core Java Design Patterns and understand them with the help of examples.
The Singleton pattern is a popular creational design pattern in Java. The Singleton pattern ensures that only one instance of a class is created and provides a global point of access to it. This can be useful when you want to restrict the instantiation of a class to a single object.
Here is an example of the Singleton creational design pattern:
public class Singleton {
// Private static instance variable
private static Singleton instance;
// Private constructor to prevent instantiation from outside the class
private Singleton() {
}
// Public static method to get the instance of the Singleton class
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
// Other methods of the Singleton class
public void someMethod() {
System.out.println("Singleton method called");
}
// Main method to test the Singleton class
public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.someMethod();
}
}
In this example, the class Singleton has a private static instance variable instance, which is the single instance of the class. The constructor is private, preventing the instantiation of the class from outside. The getInstance() method provides the global access point to the instance. It uses double-checked locking to ensure thread safety during the creation of the instance.
In this usage, getInstance() returns the instance of the Singleton class, and you can then call methods on that instance.
One common structural design pattern in Java is the Adapter pattern. The Adapter pattern allows incompatible interfaces to work together by creating a bridge between them. It is useful when you want to make existing classes work with others without modifying their source code.
Here is an example of the Adapter structural design pattern:
(You must make separate .java files for all these portions of code in the same directory in order to run the program.)
// Adaptee (Incompatible interface)
class LegacyRectangle {
public void draw(int x, int y, int width, int height) {
System.out.println("LegacyRectangle: draw(x: " + x + ", y: " + y + ", width: " + width + ", height: " + height + ")");
}
}
// Target (Desired interface)
interface Shape {
void draw(int x, int y, int width, int height);
}
// Adapter (Adapts the Adaptee to the Target interface)
class RectangleAdapter implements Shape {
private LegacyRectangle legacyRectangle;
public RectangleAdapter(LegacyRectangle legacyRectangle) {
this.legacyRectangle = legacyRectangle;
}
@Override
public void draw(int x, int y, int width, int height) {
legacyRectangle.draw(x, y, x + width, y + height);
}
}
// Client
public class Client {
public static void main(String[] args) {
// Create an instance of the Adaptee (LegacyRectangle)
LegacyRectangle legacyRectangle = new LegacyRectangle();
// Create an instance of the Adapter (RectangleAdapter)
Shape shape = new RectangleAdapter(legacyRectangle);
// Use the Adapter to draw a shape
shape.draw(10, 20, 30, 40);
}
}
In this example, we have an existing class LegacyRectangle, which represents an incompatible interface. The Shape interface represents the desired interface. The RectangleAdapter class acts as an adapter, implementing the Shape interface and adapting the LegacyRectangle class.
The RectangleAdapter class takes an instance of LegacyRectangle in its constructor and delegates the draw method call to the corresponding method of LegacyRectangle, adapting the arguments if needed.
In the Client class, we create an instance of the LegacyRectangle (the Adaptee) and an instance of the RectangleAdapter (the Adapter). We then use the Shape interface to call the draw method, which internally calls the draw method of the LegacyRectangle class.
The Adapter pattern allows the incompatible LegacyRectangle class to work with the desired Shape interface by using the RectangleAdapter.
Let us take the example of the Observer pattern to understand behavioral design patterns in Java. The Observer pattern defines a one-to-many dependency between objects, where when one object (subject) changes its state, all its dependents (observers) are notified and updated automatically. This pattern promotes loose coupling between objects.
Here is an example of the Observer behavior design pattern:
import java.util.ArrayList;
import java.util.List;
// Subject (Observable)
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
// Concrete Subject
class WeatherStation implements Subject {
private double temperature;
private List<Observer> observers;
public WeatherStation() {
observers = new ArrayList<>();
}
public void setTemperature(double temperature) {
this.temperature = temperature;
notifyObservers();
}
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature);
}
}
}
// Observer
interface Observer {
void update(double temperature);
}
// Concrete Observer
class TemperatureDisplay implements Observer {
@Override
public void update(double temperature) {
System.out.println("Temperature Display: The current temperature is " + temperature + " degrees Celsius");
}
}
// Client
public class Client {
public static void main(String[] args) {
// Create a weather station (subject)
WeatherStation weatherStation = new WeatherStation();
// Create temperature display (observer)
TemperatureDisplay temperatureDisplay = new TemperatureDisplay();
// Register the temperature display as an observer
weatherStation.registerObserver(temperatureDisplay);
// Simulate a temperature change
weatherStation.setTemperature(25.5);
}
}
In this example, we have a WeatherStation class representing the subject (observable) that maintains the temperature. It keeps track of a list of observers and notifies them whenever the temperature changes. The TemperatureDisplay class represents an observer that displays the current temperature.
The Subject interface defines methods to register, remove, and notify observers. The Observer interface declares the update method that is called by the subject when a change occurs. The WeatherStation and TemperatureDisplay classes implement the respective interfaces and define the concrete implementations.
In the Client class, we create an instance of the WeatherStation (subject) and the TemperatureDisplay (observer). We register the TemperatureDisplay as an observer to the WeatherStation using the registerObserver method. Finally, we simulate a temperature change by calling the setTemperature method on the WeatherStation, which triggers the notification to the registered observer.
The Observer pattern allows the TemperatureDisplay (observer) to automatically update its display when the WeatherStation (subject) changes its temperature.
This tutorial showed how Java design patterns solve recurring programming problems. You learned the various types of design patterns, namely, behavioral, creational, and structural design patterns. You also learned about the benefit of using design patterns which gives independence to the designer in choosing the suitable platform, solution type, and many more.
You can employ design patterns in software engineering to scale your software, manage complex codes, and provide solutions for recurring issues. In addition to learning from tutorials like these, you can learn more about Java by enrolling in various professional courses from upGrad to grow as a successful future software developer.
1. java.util.iterator is an example of which design pattern?
java.util.iterator is an example of a behavioral pattern.
2. Can a specific design pattern solve all recurring programming issues?
No, design patterns are specific to certain recurring programming issues.
3. Being a novice in Java, is it essential to learn design patterns?
It is not a must, but learning about design patterns will benefit the developer in scaling their problem-solving skills.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...