Posts

Showing posts with the label Design Patterns

Visitor Pattern

Image
In Visitor pattern, we use a visitor class which changes the executing algorithm of an element class. By this way, execution algorithm of element can vary as and when visitor varies. As per the pattern, element object has to accept the visitor object so that visitor object handles the operation on the element object. Implementation We are going to create a  ComputerPart  interface defining accept opearation. Keyboard ,  Mouse ,  Monitor  and  Computer  are concrete classes implementing  ComputerPart  interface. We will define another interface  ComputerPartVisitor  which will define a visitor class operations.  Computer  uses concrete visitor to do corresponding action. VisitorPatternDemo , our demo class, will use  Computer  and  ComputerPartVisitor  classes to demonstrate use of visitor pattern. Step 1 Define an interface to represent element. ComputerPart.java public interface Compu...

Template Pattern

Image
Template Pattern A Template Pattern says that "just define the skeleton of a function in an operation, deferring some steps to its subclasses".  Or,  Template method design pattern is to define an algorithm as skeleton of operations and leave the details to be implemented by the child classes. The overall structure and sequence of the algorithm is preserved by the parent class. Template means Preset format like HTML templates which has fixed preset format.Similarly in template method pattern,we have a preset structure method called template method which consists of steps.This steps can be abstract method which will be implemented by its subclasses. Benefits: It is very common technique for reusing the code.This is only the main benefit of it. Usage: It is used when the common behavior among sub-classes should be moved to a single common class by avoiding the duplication. UML for Template Pattern: Implementation of Template Pattern: Step 1: Creat...

Strategy Pattern

Image
Strategy Pattern A Strategy Pattern says that "defines a family of functionality, encapsulate each one, and make them interchangeable". That is, i n Strategy pattern, a class behaviour or its algorithm can be changed at run time. The Strategy Pattern is also known as Policy. Benefits: It provides a substitute to sub-classing. It defines each behaviour within its own class, eliminating the need for conditional statements. It makes it easier to extend and incorporate new behaviour without changing the application. Usage: When the multiple classes differ only in their behaviours.e.g. Servlet API. It is used when you need different variations of an algorithm. Strategy Pattern in (Core Java API's) or JSE 7 API's: Strategy Pattern in (Advance Java API's) or JEE 7 API's: Comparing our design to the definition of strategy pattern encapsulated kick and jump behaviors are two families of algorithms. And these algorithms are interchange...