7) Observer design pattern(Publish/Subscribe) :- This pattern falls under behavioral design pattern. This pattern defines a one-to-many dependency between objects so that when one object state is change then all of its dependents are notified and updated automatically. In this pattern the objects that listen or watch for change are called observers and the object that is being watched for is called subject. It is mainly used to implement distributed event handling systems. Most of the programming libraries and system including GUI toolkits have implemented this design pattern.
As per GOF:- “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”
Observer design pattern in Real World:- Most of the time, we have used online shopping, so whenever we searched for any product and suppose at that point of time it is not available then there is an option available i.e. "Notify me when product is available". If we will choose that option then whenever that product is available then we will get notification by mail or sms(Here when product is available means product state changes then we will get notification). In this case, Product is subject and we are observers.
Similarly in facebook, If we subscribe someone then whenever new updates raises by him then we will get notification.
Observer design pattern in Java :-
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionAttributeListener
All implementations of java.util.EventListener (Used in Swings)
java.util.Observer/java.util.Observable
When we can use this:-
When subject doesn't know about number of observers it has.
When one object changes its state,then all other dependent objects must automatically change their state to maintain consistency
When an object should be able to notify other objects without knowing who objects are.
8) State design pattern:- This type of behavioral design pattern provides a mechanism to change behavior of an object based on the object’s state. State is used when we need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class. In this pattern, we create objects which represent various states and a context object whose behavior varies as its state object changes.
As per GOF:- “Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.”
State design pattern in real world:- As we know, A vending machine is a machine which dispenses items such as snacks, beverages, alcohol, cigarettes, lottery tickets, cologne, consumer products and even gold and gems to customers automatically, after the customer inserts currency or credit into the machine. So this vending machines maintain its internal state which allow it to change it's behaviour depends on situation. For example, if there is no change available, it will demand exact currency. When something is out of stock, it will not deliver any product.
Another example is a drawing program like MSPaint where the program has a mouse cursor, which at any point in time can act as one of several tools. like eraser, pensil e.t.c. So, instead of switching between multiple cursor objects, the cursor maintains an internal state representing the tool currently in use. When a tool-dependent method is called (say, as a result of a mouse click), the method call is passed on to the cursor's state.
State design pattern in Java :-
9)Strategy design pattern:- This behavioral pattern is also known as policy pattern. An object controls which of a family of methods is called. Each method is in its' own class that extends a common base class. The Strategy pattern help us to build a software as a loosely coupled collection of interchangeable parts which makes our software much more extensible, maintainable, and reusable.
The strategy pattern tells do the below things
It defines a family of algorithms,
encapsulates each one(algorithm), and
It makes the algorithms interchangeable within that family.
The best example of Strategy pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways.
In Strategy design pattern:-
Algorithms (strategies) are chosen at runtime.
A Strategy is dynamically selected by a client i.e. a user or consuming program or by the Context.
Our driver or controller class is typically named as Context.
The Context class is aware of a variety of different algorithms, and each algorithm is considered as a Strategy. The Context class is responsible for handling the data during the interaction with the client.
As per GOF:- “Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour.”
Uses:-
Advantages:-
Provides an alternative to subclassing.
Reduces multiple conditional statements in a client.
Can be used to hide data that an algorithm uses that clients shouldn't know about.
Hides complex, algorithmic-specific data from the client.
Strategy design pattern in real world:- In many applications we are saving the files in different formats like: doc format(Ms-Word), ODT(OpenOffice), RTF, HTML, plain text.
Compress files using different compression algorithms by different application like winzip, winrar, 7Zip e.t.c.
Display calendars, with different holidays for different countries.
Strategy design pattern in Java:-
javax.servlet.Filter#doFilter()
java.util.Comparator#compare(), executed by among others Collections#sort().
javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
10) Template method design pattern:- This design pattern also fall under behavioural design pattern. In the template method design pattern, the 'template method' defines the common steps of an algorithm. The implementation of these steps can be deferred based on subclasses. Thus, the common algorithm is defined in the template method, but the exact steps of this algorithm can be defined in subclasses and the template method is implemented in an abstract class.
As per GOF:- “Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.”
When to use: -
When we have a predefined steps for algorithm but implementation of those steps may vary.
When we want to avoid code duplication,implementing common code in base class and variation in subclass.
Template method design pattern in real world:-Making of every automobile and machines are based on some template pattern. Basic building plans because a different building may have many variations. For creating any framework, we need to use this design pattern in order to remove code duplication.
Template method design pattern in Java:-
javax.servlet.http.HttpServlet, all the doXXX() methods by default sends a HTTP 405 "Method Not Allowed" error to the response. We are free to implement none or any of them.
All non-abstract methods of java.io.InputStream, java.io.OutputStream, java.io.Reader and java.io.Writer.
All non-abstract methods of java.util.AbstractList, java.util.AbstractSet and java.util.AbstractMap.
11) Visitor design pattern:- This pattern falls under behavioral design pattern. This pattern is used when we have to perform an operation on a group of similar kind of Objects. Using this design pattern, we can move the operational logic from the objects to another class. This pattern is providing a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.
As of GOF:- “Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure. ”
Visitor design pattern in Real world:- Visitor pattern is a design pattern commonly used in the parser of a compiler, such as Eclipse JDT AST Parser.
Visitor design pattern in Java:-
javax.lang.model.type.TypeMirror and TypeVisitor
javax.lang.model.element.AnnotationValue and AnnotationValueVisitor
javax.lang.model.element.Element and ElementVisitor
Uses:-
When the classes defining the object structure changes rarely, but we often want to define new operations over the structure. (If the object structure classes change often, then it's probably better to define the operations in those classes.)
When many distinct and unrelated operations need to be performed on objects in an object structure, and we don't want to spoil their classes with these operations
When an object structure contains many classes of objects with differing interfaces, and we want to perform operations on these objects that depend on their concrete classes
Advantages:-
Adding new operations is easy
Related behavior isn't spread over the classes defining the object structure; it's localized in a visitor. Unrelated sets of behavior are partitioned in their own visitor subclasses.
Difference between Visitor and Strategy pattern:-
Visitor and strategy looks similar as they encapsulates complex logic from data. We can say that Visitor design pattern is more general form of strategy. In Strategy design pattern we have one context on which multiple algorithms operate means in Strategy pattern we have a single context and multiple algorithms work on it. But on the other way Visitor design pattern have multiple contexts and for every context we have an algorithm.
In short, We can generalize that Strategy is a special kind of Visitor, In strategy we have one data context and multiple algorithms while in visitor for every data context, one algorithm associated with that.