Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Java Design Patterns

License

NotificationsYou must be signed in to change notification settings

learning-zone/java-design-patterns

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Click ★ if you like the project. Your contributions are heartily ♡ welcome.


Q. Exaplain MVC, Front-Controller, DAO, DTO, Service-Locator, Prototype design patterns?

2. Front-Controller:

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.

  • Front Controller - Single handler for all kinds of requests coming to the application (either web based/ desktop based).

  • Dispatcher - Front Controller may use a dispatcher object which can dispatch the request to corresponding specific handler.

  • View - Views are the object for which the requests are made.

Example:

We are going to create aFrontController andDispatcher to act as Front Controller and Dispatcher correspondingly.HomeView andStudentView represent various views for which requests can come to front controller.

FrontControllerPatternDemo, our demo class, will use FrontController to demonstrate Front Controller Design Pattern.

Step 1Create Views.

HomeView.java

publicclassHomeView {publicvoidshow(){System.out.println("Displaying Home Page");   }}

StudentView.java

publicclassStudentView {publicvoidshow(){System.out.println("Displaying Student Page");   }}

Step2Create Dispatcher.

Dispatcher.java

publicclassDispatcher {privateStudentViewstudentView;privateHomeViewhomeView;publicDispatcher(){studentView =newStudentView();homeView =newHomeView();   }publicvoiddispatch(Stringrequest){if(request.equalsIgnoreCase("STUDENT")){studentView.show();      }else{homeView.show();      }   }}

Step3Create FrontController.

FrontController.java

publicclassFrontController {privateDispatcherdispatcher;publicFrontController(){dispatcher =newDispatcher();   }privatebooleanisAuthenticUser(){System.out.println("User is authenticated successfully.");returntrue;   }privatevoidtrackRequest(Stringrequest){System.out.println("Page requested: " +request);   }publicvoiddispatchRequest(Stringrequest){//log each requesttrackRequest(request);//authenticate the userif(isAuthenticUser()){dispatcher.dispatch(request);      }   }}

Step4Use the FrontController to demonstrate Front Controller Design Pattern.

FrontControllerPatternDemo.java

publicclassFrontControllerPatternDemo {publicstaticvoidmain(String[]args) {FrontControllerfrontController =newFrontController();frontController.dispatchRequest("HOME");frontController.dispatchRequest("STUDENT");   }}

Q. What are the design patterns available in Java?

Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns.

1. Creational Design Patterns

  • Singleton Pattern
  • Factory Pattern
  • Abstract Factory Pattern
  • Builder Pattern
  • Prototype Pattern

2. Structural Design Patterns

  • Adapter Pattern
  • Composite Pattern
  • Proxy Pattern
  • Flyweight Pattern
  • Facade Pattern
  • Bridge Pattern
  • Decorator Pattern

3. Behavioral Design Patterns

  • Template Method Pattern
  • Mediator Pattern
  • Chain of Responsibility Pattern
  • Observer Pattern
  • Strategy Pattern
  • Command Pattern
  • State Pattern
  • Visitor Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Memento Pattern

4. Miscellaneous Design Patterns

  • DAO Design Pattern
  • Dependency Injection Pattern
  • MVC Pattern

Q. Explain Singleton Design Pattern in Java?

1. Eager initialization:
In eager initialization, the instance of Singleton Class is created at the time of class loading.

Example:

publicclassEagerInitializedSingleton {privatestaticfinalEagerInitializedSingletoninstance =newEagerInitializedSingleton();// private constructor to avoid client applications to use constructorprivateEagerInitializedSingleton(){}publicstaticEagerInitializedSingletongetInstance(){returninstance;    }}

2. Static block initialization
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.

Example:

publicclassStaticBlockSingleton  {privatestaticStaticBlockSingletoninstance;privateStaticBlockSingleton (){}// static block initialization for exception handlingstatic{try{instance =newStaticBlockSingleton ();        }catch(Exceptione){thrownewRuntimeException("Exception occured in creating Singleton instance");        }    }publicstaticStaticBlockSingletongetInstance(){returninstance;    }}

3. Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method.

Example:

publicclassLazyInitializedSingleton  {privatestaticLazyInitializedSingletoninstance;privateLazyInitializedSingleton(){}publicstaticLazyInitializedSingletongetInstance(){if(instance ==null){instance =newLazyInitializedSingleton ();        }returninstance;    }}

4. Thread Safe Singleton
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.

Example:

publicclassThreadSafeSingleton {privatestaticThreadSafeSingletoninstance;privateThreadSafeSingleton(){}publicstaticsynchronizedThreadSafeSingletongetInstance(){if(instance ==null){instance =newThreadSafeSingleton();        }returninstance;    }}

5. Bill Pugh Singleton Implementation
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.

Example:

publicclassBillPughSingleton {privateBillPughSingleton(){}privatestaticclassSingletonHelper{privatestaticfinalBillPughSingletonINSTANCE =newBillPughSingleton();    }publicstaticBillPughSingletongetInstance(){returnSingletonHelper.INSTANCE;    }}

Q. Explain Adapter Design Pattern in Java?

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.

Example:

we have two incompatible interfaces:MediaPlayer andMediaPackage. 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.

MediaPlayer.java

publicinterfaceMediaPlayer {voidplay(Stringfilename);}

MediaPackage.java

publicinterfaceMediaPackage {voidplayFile(Stringfilename);}

MP3.java

publicclassMP3implementsMediaPlayer {@Overridepublicvoidplay(Stringfilename) {System.out.println("Playing MP3 File " +filename); }}

MP4.java

publicclassMP4implementsMediaPackage {@OverridepublicvoidplayFile(Stringfilename) {System.out.println("Playing MP4 File " +filename);    }}

VLC.java

publicclassVLCimplementsMediaPackage {@OverridepublicvoidplayFile(Stringfilename) {System.out.println("Playing VLC File " +filename);    }}

FormatAdapter.java

publicclassFormatAdapterimplementsMediaPlayer {privateMediaPackagemedia;publicFormatAdapter(MediaPackagem) {media =m;    }@Overridepublicvoidplay(Stringfilename) {System.out.print("Using Adapter --> ");media.playFile(filename);    }}

Main.java

publicclassMain {publicstaticvoidmain(String[]args) {MediaPlayerplayer =newMP3();player.play("file.mp3");player =newFormatAdapter(newMP4());player.play("file.mp4");player =newFormatAdapter(newVLC());player.play("file.avi");    }}

Q. Explain Factory Design Pattern in Java?

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.

Example: Calculate Electricity BillPlan.java

importjava.io.*;abstractclassPlan {protecteddoublerate;abstractvoidgetRate();publicvoidcalculateBill(intunits){System.out.println(units*rate);      }  }

DomesticPlan.java

classDomesticPlanextendsPlan{@overridepublicvoidgetRate(){rate=3.50;                  }  }

CommercialPlan.java

classCommercialPlanextendsPlan{@overridepublicvoidgetRate(){rate=7.50;      }   }

InstitutionalPlan.java

classInstitutionalPlanextendsPlan{@overridepublicvoidgetRate(){rate=5.50;     }   }

GetPlanFactory.java

classGetPlanFactory {// use getPlan method to get object of type PlanpublicPlangetPlan(StringplanType){if(planType ==null){returnnull;          }if(planType.equalsIgnoreCase("DOMESTICPLAN")) {returnnewDomesticPlan();              }elseif(planType.equalsIgnoreCase("COMMERCIALPLAN")){returnnewCommercialPlan();          }elseif(planType.equalsIgnoreCase("INSTITUTIONALPLAN")) {returnnewInstitutionalPlan();          }returnnull;      }  }

GenerateBill.java

importjava.io.*;classGenerateBill {publicstaticvoidmain(Stringargs[])throwsIOException {GetPlanFactoryplanFactory =newGetPlanFactory();System.out.print("Enter the name of plan for which the bill will be generated: ");BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));StringplanName=br.readLine();System.out.print("Enter the number of units for bill will be calculated: ");intunits=Integer.parseInt(br.readLine());Planp =planFactory.getPlan(planName);// call getRate() method and calculateBill()method of DomesticPaln.System.out.print("Bill amount for "+planName+" of  "+units+" units is: ");p.getRate();p.calculateBill(units);      }  }

Q. Explain Strategy Design Pattern in Java?

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.

Example: Simple Shopping Cart where we have two payment strategies – using Credit Card or using PayPal.

PaymentStrategy.java

publicinterfacePaymentStrategy {publicvoidpay(intamount);}

CreditCardStrategy.java

publicclassCreditCardStrategyimplementsPaymentStrategy {privateStringname;privateStringcardNumber;privateStringcvv;privateStringdateOfExpiry;publicCreditCardStrategy(Stringnm,StringccNum,Stringcvv,StringexpiryDate){this.name=nm;this.cardNumber=ccNum;this.cvv=cvv;this.dateOfExpiry=expiryDate;}@Overridepublicvoidpay(intamount) {System.out.println(amount +" paid with credit/debit card");}}

PaypalStrategy.java

publicclassPaypalStrategyimplementsPaymentStrategy {privateStringemailId;privateStringpassword;publicPaypalStrategy(Stringemail,Stringpwd){this.emailId=email;this.password=pwd;}@Overridepublicvoidpay(intamount) {System.out.println(amount +" paid using Paypal.");}}

Item.java

publicclassItem {privateStringupcCode;privateintprice;publicItem(Stringupc,intcost){this.upcCode=upc;this.price=cost;}publicStringgetUpcCode() {returnupcCode;}publicintgetPrice() {returnprice;}}

ShoppingCart.java

importjava.text.DecimalFormat;importjava.util.ArrayList;importjava.util.List;publicclassShoppingCart {List<Item>items;publicShoppingCart(){this.items=newArrayList<Item>();}publicvoidaddItem(Itemitem){this.items.add(item);}publicvoidremoveItem(Itemitem){this.items.remove(item);}publicintcalculateTotal(){intsum =0;for(Itemitem :items){sum +=item.getPrice();}returnsum;}publicvoidpay(PaymentStrategypaymentMethod){intamount =calculateTotal();paymentMethod.pay(amount);}}

ShoppingCartTest.java

publicclassShoppingCartTest {publicstaticvoidmain(String[]args) {ShoppingCartcart =newShoppingCart();Itemitem1 =newItem("1234",10);Itemitem2 =newItem("5678",40);cart.addItem(item1);cart.addItem(item2);// pay by paypalcart.pay(newPaypalStrategy("myemail@example.com","mypwd"));// pay by credit cardcart.pay(newCreditCardStrategy("Pankaj Kumar","1234567890123456","786","12/15"));}}

Output

500 paid using Paypal.500 paid with credit/debit card

Q. When do you use Flyweight pattern?

Q. What is difference between dependency injection and factory design pattern?

Q. Difference between Adapter and Decorator pattern?

Q. Difference between Adapter and Proxy Pattern?

Q. What is Template method pattern?

Q. When do you use Visitor design pattern?

Q. When do you use Composite design pattern?

Q. Difference between Abstract factory and Prototype design pattern?

About

Java Design Patterns

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp