├── _config.yaml ├── assets └── star.png ├── LICENSE └── README.md /_config.yaml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman 2 | -------------------------------------------------------------------------------- /assets/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/learning-zone/java-design-patterns/HEAD/assets/star.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Pradeep Kumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java Design Patterns 2 | 3 | > *Click ★ if you like the project. Your contributions are heartily ♡ welcome.* 4 | 5 |
6 | 7 | ## Q. Exaplain MVC, Front-Controller, DAO, DTO, Service-Locator, Prototype design patterns? 8 | 9 | **2. Front-Controller:** 10 | 11 | The front controller design pattern is used to provide a centralized request handling mechanism so that all requests will be handled by a single handler. This handler can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern. 12 | 13 | * Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based). 14 | 15 | * Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler. 16 | 17 | * View - Views are the object for which the requests are made. 18 | 19 | *Example:* 20 | 21 | We are going to create a `FrontController` and `Dispatcher` to act as Front Controller and Dispatcher correspondingly. `HomeView` and `StudentView` represent various views for which requests can come to front controller. 22 | 23 | FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate Front Controller Design Pattern. 24 | 25 | Step 1 26 | Create Views. 27 | 28 | *HomeView.java* 29 | ```java 30 | public class HomeView { 31 | public void show(){ 32 | System.out.println("Displaying Home Page"); 33 | } 34 | } 35 | ``` 36 | *StudentView.java* 37 | ```java 38 | public class StudentView { 39 | public void show(){ 40 | System.out.println("Displaying Student Page"); 41 | } 42 | } 43 | ``` 44 | 45 | Step2 46 | Create Dispatcher. 47 | 48 | *Dispatcher.java* 49 | ```java 50 | public class Dispatcher { 51 | private StudentView studentView; 52 | private HomeView homeView; 53 | 54 | public Dispatcher(){ 55 | studentView = new StudentView(); 56 | homeView = new HomeView(); 57 | } 58 | 59 | public void dispatch(String request){ 60 | if(request.equalsIgnoreCase("STUDENT")){ 61 | studentView.show(); 62 | } 63 | else{ 64 | homeView.show(); 65 | } 66 | } 67 | } 68 | ``` 69 | 70 | Step3 71 | Create FrontController. 72 | 73 | *FrontController.java* 74 | ```java 75 | public class FrontController { 76 | 77 | private Dispatcher dispatcher; 78 | 79 | public FrontController(){ 80 | dispatcher = new Dispatcher(); 81 | } 82 | 83 | private boolean isAuthenticUser(){ 84 | System.out.println("User is authenticated successfully."); 85 | return true; 86 | } 87 | 88 | private void trackRequest(String request){ 89 | System.out.println("Page requested: " + request); 90 | } 91 | 92 | public void dispatchRequest(String request){ 93 | //log each request 94 | trackRequest(request); 95 | 96 | //authenticate the user 97 | if(isAuthenticUser()){ 98 | dispatcher.dispatch(request); 99 | } 100 | } 101 | } 102 | ``` 103 | 104 | Step4 105 | Use the FrontController to demonstrate Front Controller Design Pattern. 106 | 107 | *FrontControllerPatternDemo.java* 108 | ```java 109 | public class FrontControllerPatternDemo { 110 | public static void main(String[] args) { 111 | 112 | FrontController frontController = new FrontController(); 113 | frontController.dispatchRequest("HOME"); 114 | frontController.dispatchRequest("STUDENT"); 115 | } 116 | } 117 | ``` 118 | 119 |
120 | ↥ back to top 121 |
122 | 123 | ## Q. What are the design patterns available in Java? 124 | 125 | Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns. 126 | 127 | **1. Creational Design Patterns** 128 | 129 | * Singleton Pattern 130 | * Factory Pattern 131 | * Abstract Factory Pattern 132 | * Builder Pattern 133 | * Prototype Pattern 134 | 135 | **2. Structural Design Patterns** 136 | 137 | * Adapter Pattern 138 | * Composite Pattern 139 | * Proxy Pattern 140 | * Flyweight Pattern 141 | * Facade Pattern 142 | * Bridge Pattern 143 | * Decorator Pattern 144 | 145 | **3. Behavioral Design Patterns** 146 | 147 | * Template Method Pattern 148 | * Mediator Pattern 149 | * Chain of Responsibility Pattern 150 | * Observer Pattern 151 | * Strategy Pattern 152 | * Command Pattern 153 | * State Pattern 154 | * Visitor Pattern 155 | * Interpreter Pattern 156 | * Iterator Pattern 157 | * Memento Pattern 158 | 159 | **4. Miscellaneous Design Patterns** 160 | 161 | * DAO Design Pattern 162 | * Dependency Injection Pattern 163 | * MVC Pattern 164 | 165 |
166 | ↥ back to top 167 |
168 | 169 | ## Q. Explain Singleton Design Pattern in Java? 170 | 171 | **1. Eager initialization:** 172 | In eager initialization, the instance of Singleton Class is created at the time of class loading. 173 | 174 | Example: 175 | ```java 176 | public class EagerInitializedSingleton { 177 | 178 | private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); 179 | 180 | // private constructor to avoid client applications to use constructor 181 | private EagerInitializedSingleton(){} 182 | 183 | public static EagerInitializedSingleton getInstance(){ 184 | return instance; 185 | } 186 | } 187 | ``` 188 | 189 | **2. Static block initialization** 190 | Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling. 191 | 192 | Example: 193 | ```java 194 | public class StaticBlockSingleton { 195 | 196 | private static StaticBlockSingleton instance; 197 | 198 | private StaticBlockSingleton (){} 199 | 200 | // static block initialization for exception handling 201 | static{ 202 | try{ 203 | instance = new StaticBlockSingleton (); 204 | }catch(Exception e){ 205 | throw new RuntimeException("Exception occured in creating Singleton instance"); 206 | } 207 | } 208 | 209 | public static StaticBlockSingleton getInstance(){ 210 | return instance; 211 | } 212 | } 213 | ``` 214 | 215 | **3. Lazy Initialization** 216 | Lazy initialization method to implement Singleton pattern creates the instance in the global access method. 217 | 218 | Example: 219 | ```java 220 | public class LazyInitializedSingleton { 221 | 222 | private static LazyInitializedSingleton instance; 223 | 224 | private LazyInitializedSingleton(){} 225 | 226 | public static LazyInitializedSingleton getInstance(){ 227 | if(instance == null){ 228 | instance = new LazyInitializedSingleton (); 229 | } 230 | return instance; 231 | } 232 | } 233 | ``` 234 | 235 | **4. Thread Safe Singleton** 236 | The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. 237 | 238 | Example: 239 | ```java 240 | public class ThreadSafeSingleton { 241 | 242 | private static ThreadSafeSingleton instance; 243 | 244 | private ThreadSafeSingleton(){} 245 | 246 | public static synchronized ThreadSafeSingleton getInstance(){ 247 | if(instance == null){ 248 | instance = new ThreadSafeSingleton(); 249 | } 250 | return instance; 251 | } 252 | } 253 | ``` 254 | 255 | **5. Bill Pugh Singleton Implementation** 256 | Prior to Java5, memory model had a lot of issues and above methods caused failure in certain scenarios in multithreaded environment. So, Bill Pugh suggested a concept of inner static classes to use for singleton. 257 | 258 | Example: 259 | ```java 260 | public class BillPughSingleton { 261 | 262 | private BillPughSingleton(){} 263 | 264 | private static class SingletonHelper{ 265 | private static final BillPughSingleton INSTANCE = new BillPughSingleton(); 266 | } 267 | 268 | public static BillPughSingleton getInstance(){ 269 | return SingletonHelper.INSTANCE; 270 | } 271 | } 272 | ``` 273 | 274 |
275 | ↥ back to top 276 |
277 | 278 | ## Q. Explain Adapter Design Pattern in Java? 279 | 280 | Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter. 281 | 282 | Example: 283 | 284 | we have two incompatible interfaces: **MediaPlayer** and **MediaPackage**. MP3 class is an implementation of the MediaPlayer interface and we have VLC and MP4 as implementations of the MediaPackage interface. We want to use MediaPackage implementations as MediaPlayer instances. So, we need to create an adapter to help to work with two incompatible classes. 285 | 286 | MediaPlayer.java 287 | ```java 288 | public interface MediaPlayer { 289 | void play(String filename); 290 | } 291 | ``` 292 | 293 | MediaPackage.java 294 | ```java 295 | public interface MediaPackage { 296 | void playFile(String filename); 297 | } 298 | ``` 299 | 300 | MP3.java 301 | ```java 302 | public class MP3 implements MediaPlayer { 303 | @Override 304 | public void play(String filename) { 305 | System.out.println("Playing MP3 File " + filename); 306 | } 307 | } 308 | ``` 309 | 310 | MP4.java 311 | ```java 312 | public class MP4 implements MediaPackage { 313 | @Override 314 | public void playFile(String filename) { 315 | System.out.println("Playing MP4 File " + filename); 316 | } 317 | } 318 | ``` 319 | 320 | VLC.java 321 | ```java 322 | public class VLC implements MediaPackage { 323 | @Override 324 | public void playFile(String filename) { 325 | System.out.println("Playing VLC File " + filename); 326 | } 327 | } 328 | ``` 329 | 330 | FormatAdapter.java 331 | ```java 332 | public class FormatAdapter implements MediaPlayer { 333 | private MediaPackage media; 334 | public FormatAdapter(MediaPackage m) { 335 | media = m; 336 | } 337 | @Override 338 | public void play(String filename) { 339 | System.out.print("Using Adapter --> "); 340 | media.playFile(filename); 341 | } 342 | } 343 | ``` 344 | 345 | Main.java 346 | ```java 347 | public class Main { 348 | public static void main(String[] args) { 349 | MediaPlayer player = new MP3(); 350 | player.play("file.mp3"); 351 | player = new FormatAdapter(new MP4()); 352 | player.play("file.mp4"); 353 | player = new FormatAdapter(new VLC()); 354 | player.play("file.avi"); 355 | } 356 | } 357 | ``` 358 | 359 |
360 | ↥ back to top 361 |
362 | 363 | ## Q. Explain Factory Design Pattern in Java? 364 | 365 | A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of the class. 366 | 367 | Example: Calculate Electricity Bill 368 | Plan.java 369 | 370 | ```java 371 | import java.io.*; 372 | abstract class Plan { 373 | protected double rate; 374 | abstract void getRate(); 375 | 376 | public void calculateBill(int units){ 377 | System.out.println(units*rate); 378 | } 379 | } 380 | ``` 381 | 382 | DomesticPlan.java 383 | ```java 384 | class DomesticPlan extends Plan{ 385 | @override 386 | public void getRate(){ 387 | rate=3.50; 388 | } 389 | } 390 | ``` 391 | 392 | CommercialPlan.java 393 | ```java 394 | class CommercialPlan extends Plan{ 395 | @override 396 | public void getRate(){ 397 | rate=7.50; 398 | } 399 | } 400 | ``` 401 | 402 | InstitutionalPlan.java 403 | ```java 404 | class InstitutionalPlan extends Plan{ 405 | @override 406 | public void getRate(){ 407 | rate=5.50; 408 | } 409 | } 410 | ``` 411 | 412 | GetPlanFactory.java 413 | ```java 414 | class GetPlanFactory { 415 | 416 | // use getPlan method to get object of type Plan 417 | public Plan getPlan(String planType){ 418 | if(planType == null){ 419 | return null; 420 | } 421 | if(planType.equalsIgnoreCase("DOMESTICPLAN")) { 422 | return new DomesticPlan(); 423 | } 424 | else if(planType.equalsIgnoreCase("COMMERCIALPLAN")){ 425 | return new CommercialPlan(); 426 | } 427 | else if(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) { 428 | return new InstitutionalPlan(); 429 | } 430 | return null; 431 | } 432 | } 433 | ``` 434 | 435 | GenerateBill.java 436 | ```java 437 | import java.io.*; 438 | class GenerateBill { 439 | 440 | public static void main(String args[])throws IOException { 441 | GetPlanFactory planFactory = new GetPlanFactory(); 442 | 443 | System.out.print("Enter the name of plan for which the bill will be generated: "); 444 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 445 | 446 | String planName=br.readLine(); 447 | System.out.print("Enter the number of units for bill will be calculated: "); 448 | int units=Integer.parseInt(br.readLine()); 449 | 450 | Plan p = planFactory.getPlan(planName); 451 | // call getRate() method and calculateBill()method of DomesticPaln. 452 | 453 | System.out.print("Bill amount for "+planName+" of "+units+" units is: "); 454 | p.getRate(); 455 | p.calculateBill(units); 456 | } 457 | } 458 | ``` 459 | 460 |
461 | ↥ back to top 462 |
463 | 464 | ## Q. Explain Strategy Design Pattern in Java? 465 | 466 | Strategy design pattern is one of the behavioral design pattern. Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime. 467 | 468 | Example: Simple Shopping Cart where we have two payment strategies – using Credit Card or using PayPal. 469 | 470 | PaymentStrategy.java 471 | ```java 472 | public interface PaymentStrategy { 473 | public void pay(int amount); 474 | } 475 | ``` 476 | 477 | CreditCardStrategy.java 478 | ```java 479 | public class CreditCardStrategy implements PaymentStrategy { 480 | 481 | private String name; 482 | private String cardNumber; 483 | private String cvv; 484 | private String dateOfExpiry; 485 | 486 | public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ 487 | this.name=nm; 488 | this.cardNumber=ccNum; 489 | this.cvv=cvv; 490 | this.dateOfExpiry=expiryDate; 491 | } 492 | @Override 493 | public void pay(int amount) { 494 | System.out.println(amount +" paid with credit/debit card"); 495 | } 496 | } 497 | ``` 498 | 499 | PaypalStrategy.java 500 | ```java 501 | public class PaypalStrategy implements PaymentStrategy { 502 | 503 | private String emailId; 504 | private String password; 505 | 506 | public PaypalStrategy(String email, String pwd){ 507 | this.emailId=email; 508 | this.password=pwd; 509 | } 510 | @Override 511 | public void pay(int amount) { 512 | System.out.println(amount + " paid using Paypal."); 513 | } 514 | } 515 | ``` 516 | 517 | Item.java 518 | ```java 519 | public class Item { 520 | 521 | private String upcCode; 522 | private int price; 523 | 524 | public Item(String upc, int cost){ 525 | this.upcCode=upc; 526 | this.price=cost; 527 | } 528 | public String getUpcCode() { 529 | return upcCode; 530 | } 531 | public int getPrice() { 532 | return price; 533 | } 534 | } 535 | ``` 536 | 537 | ShoppingCart.java 538 | ```java 539 | import java.text.DecimalFormat; 540 | import java.util.ArrayList; 541 | import java.util.List; 542 | 543 | public class ShoppingCart { 544 | 545 | List items; 546 | 547 | public ShoppingCart(){ 548 | this.items=new ArrayList(); 549 | } 550 | public void addItem(Item item){ 551 | this.items.add(item); 552 | } 553 | public void removeItem(Item item){ 554 | this.items.remove(item); 555 | } 556 | public int calculateTotal(){ 557 | int sum = 0; 558 | for(Item item : items){ 559 | sum += item.getPrice(); 560 | } 561 | return sum; 562 | } 563 | public void pay(PaymentStrategy paymentMethod){ 564 | int amount = calculateTotal(); 565 | paymentMethod.pay(amount); 566 | } 567 | } 568 | ``` 569 | 570 | ShoppingCartTest.java 571 | ```java 572 | public class ShoppingCartTest { 573 | 574 | public static void main(String[] args) { 575 | ShoppingCart cart = new ShoppingCart(); 576 | 577 | Item item1 = new Item("1234",10); 578 | Item item2 = new Item("5678",40); 579 | 580 | cart.addItem(item1); 581 | cart.addItem(item2); 582 | 583 | // pay by paypal 584 | cart.pay(new PaypalStrategy("myemail@example.com", "mypwd")); 585 | 586 | // pay by credit card 587 | cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15")); 588 | } 589 | } 590 | ``` 591 | Output 592 | ``` 593 | 500 paid using Paypal. 594 | 500 paid with credit/debit card 595 | ``` 596 | 597 |
598 | ↥ back to top 599 |
600 | 601 | #### Q. When do you use Flyweight pattern? 602 | #### Q. What is difference between dependency injection and factory design pattern? 603 | #### Q. Difference between Adapter and Decorator pattern? 604 | #### Q. Difference between Adapter and Proxy Pattern? 605 | #### Q. What is Template method pattern? 606 | #### Q. When do you use Visitor design pattern? 607 | #### Q. When do you use Composite design pattern? 608 | #### Q. Difference between Abstract factory and Prototype design pattern? 609 | 610 |
611 | ↥ back to top 612 |
613 | --------------------------------------------------------------------------------