Posts

Showing posts with the label Design Patterns

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”. 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: Create a Game  abstract  class. / /This is an abstract class.   pub lic abstrac t class Game { abs tract void init ialize(); abstract v oid start () ; abstractvoid end () ; publicfinalvoid play () { // initialize the game initialize () ; // start game start () ; // end game end () ; } } // End of the Game abstract class. Step 2: Create a  Chess  class that will extend Game abstract class for giving the definition to its method. public class Chess extends Game { @Ov erride void initi alize() { S ystem.out.p rintln ( “ Chess Ga m e Initia

Strategy Pattern

Image
A Strategy Pattern says that “defines a family of functionality, encapsulate each one, and make them interchangeable”. The Strategy Pattern is also known as Policy. Benefits: It provides a substitute to subclassing. It defines each behavior within its own class, eliminating the need for conditional statements. It makes it easier to extend and incorporate new behavior without changing the application. Usage: When the multiple classes differ only in their behaviors.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: UML for Strategy Pattern: Implementation of Strategy Pattern: Step 1: Create a  Strategy  interface. p ublic interface Strategy { public float calculation ( float a , float b ) ; } // End of the Strategy interface. Step 2: Create a  Addition  class that will implement Startegy interface. / /This is a class.   public class Addition impl

State Pattern

Image
State Pattern A State Pattern says that “the class behavior changes based on its state”. In State Pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes. The State Pattern is also known as Objects for States. Benefits: It keeps the state-specific behavior. It makes any state transitions explicit. Usage: When the behavior of object depends on its state and it must be able to change its behavior at runtime according to the new state. It is used when the operations have large, multipart conditional statements that depend on the state of an object. UML for State Pattern: Implementation of State Pattern: Step 1: Create a  Connection  interface that will provide the connection to the Controller class. p ublic interface Connection {   public void open () ;   public void close () ;   public void log () ;   public void update () ; } // End of the Connection interface. Step 2: Create an  Accounting  class that will implem

Observer Pattern

Image
Observer Pattern An Observer Pattern says that “just define a one-to-one dependency so that when one object changes state, all its dependents are notified and updated automatically”. The Memento pattern is also known as Dependents or Publish-Subscribe. Benefits: It describes the coupling between the objects and the observer. It provides the support for broadcast-type communication. Usage: When the change of a state in one object must be reflected in another object without keeping the objects tight coupled. When the framework we writes and needs to be enhanced in future with new observers with minimal chamges. UML for Observer Pattern:   Implementation of Observer Pattern Step 1: Create a  ResponseHandler1  class the will implement the java.util.Observer interface. i mport java . util . Observable ; import java . util . Observer ; public class ResponseHandler1 implements Observer { private String resp ; publicvoid update ( Observable obj , Object arg ) { if ( arg instanceof St

Memento Pattern

Image
Memento Pattern A Memento Pattern says that “to restore the state of an object to its previous state”. But it must do this without violating Encapsulation. Such case is useful in case of error or failure. The Memento pattern is also known as  Token . Undo or backspace or ctrl+z is one of the most used operation in an editor. Memento design pattern is used to implement the undo operation. This is done by saving the current state of the object as it changes state. Benefits: It preserves encapsulation boundaries. It simplifies the originator. Usage: It is used in Undo and Redo operations in most software. It is also used in database transactions. UML for Memento Pattern: Memento: Stores internal state of the originator object. The state can include any number of state variables. The Memento must have two interfaces, an interface to the caretaker. This interface must not allow any operations or any access to internal state stored by the memento and thus maintains the encapsulation. The oth

Mediator Pattern

Image
Mediator Pattern A Mediator Pattern says that “to define an object that encapsulates how a set of objects interact”. I will explain the Mediator pattern by considering a problem. When we begin with development, we have a few classes and these classes interact with each other producing results. Now, consider slowly, the logic becomes more complex when functionality increases. Then what happens? We add more classes and they still interact with each other but it gets really difficult to maintain this code now. So, Mediator pattern takes care of this problem. Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintainability of the code by loose coupling. Benefits: It decouples the number of classes. It simplifies object protocols. It centralizes the control. The individual components become simpler and much easier to

Iterator Pattern

Image
Iterator Pattern According to GoF, Iterator Pattern is used  “to access the elements of an aggregate object sequentially without exposing its underlying implementation”. The Iterator pattern is also known as  Cursor. In collection framework, we are now using Iterator that is preferred over Enumeration. Advantage of Iterator Pattern It supports variations in the traversal of a collection. It simplifies the interface to the collection. Usage of Iterator Pattern: It is used: When you want to access a collection of objects without exposing its internal representation. When there are multiple traversals of objects need to be supported in the collection. Example of Iterator Pattern Let’s understand the example of iterator pattern pattern by the above UML diagram. UML for Iterator Pattern: Implementation of above UML Step 1 Create a  Iterartor  interface. p ublic interface Iterator {     public boolean hasNext () ;     public Object next () ; } Step 2 Create a  Container  interface. p ublic

Interpreter Pattern

Image
Interpreter Pattern An Interpreter Pattern says that  “to define a representation of grammar of a given language, along with an interpreter that uses this representation to interpret sentences in the language”. Basically the Interpreter pattern has limited area where it can be applied. We can discuss the Interpreter pattern only in terms of formal grammars but in this area there are better solutions that is why it is not frequently used. This pattern can applied for parsing the expressions defined in simple grammars and sometimes in simple rule engines. Advantage of Interpreter Pattern It is easier to change and extend the grammar. Implementing the grammar is straightforward. Usage of Interpreter pattern: It is used: When the grammar of the language is not complicated. When the efficiency is not a priority. Example of Interpreter Pattern Let’s understand the example of Interpreter Pattern by the above UML diagram. UML for Interpreter Pattern: Implementation of above UML Step 1 Create a

Command Pattern

Image
Command Pattern A Command Pattern says that “ encapsulate a request under an object as a command and pass it to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command “. It is also known as  Action or Transaction. Advantage of command pattern It separates the object that invokes the operation from the object that actually performs the operation. It makes easy to add new commands, because existing classes remain unchanged. Usage of command pattern: It is used: When you need parameterize objects according to an action perform. When you need to create and execute requests at different times. When you need to support rollback, logging or transaction functionality. Example of command pattern Let’s understand the example of adapter design pattern by the above UML diagram. UML for command pattern: These are the following participants of the Command Design pattern: Comma