Command(recognizeable by behavioral
methods in an abstract/interface type which invokes a method in an
implementation of adifferent abstract/interface
type which has been encapsulated by
the command implementation during its creation)

Interpreter(recognizeable by behavioral
methods returning a structurally different
instance/type of the given instance/type; note that parsing/formatting is not
part of the pattern, determining the pattern and how to apply it is)

According to the strategy
pattern, the behaviors of a class should not be inherited. Instead they should
be encapsulated using interfaces. As an example, consider a car class. Two
possible functionalities for car arebrakeandaccelerate.

Since accelerate and brake
behaviors change frequently between models, a common approach is to implement
these behaviors in subclasses. This approach has significant drawbacks:
accelerate and brake behaviors must be declared in each new Car model. The work
of managing these behaviors increases greatly as the number of models
increases, and requires code to be duplicated across models. Additionally, it
is not easy to determine the exact nature of the behavior for each model
without investigating the code in each.

The strategy pattern uses
aggregation instead of inheritance. In the strategy pattern, behaviors are
defined as separate interfaces and specific classes that implement these
interfaces. Specific classes encapsulate these interfaces. This allows better
decoupling between the behavior and the class that uses the behavior. The
behavior can be changed without breaking the classes that use it, and the
classes can switch between behaviors by changing the specific implementation
used without requiring any significant code changes. Behaviors can also be
changed at run-time as well as at design-time. For instance, a car object’s
brake behavior can be changed fromBrakeWithABS()toBrake()by changing thebrakeBehaviormember to:

brakeBehavior =new Brake();

This gives greater flexibility in
design and is in harmony with theOpen/closed principle(OCP) that states that classes should be open for extension but
closed for modification.

Strategy(recognizeable by behavioral
methods in an abstract/interface type which invokes a method in an
implementation of adifferent abstract/interface
type which has been passed-in as
method argument into the strategy implementation)

·javax.servlet.http.HttpServlet,
the service() and all doXXX() methods
takeHttpServletRequest and HttpServletResponse and
the implementor has to process them (and not to get hold of them as instance
variables!).

10.Template Method - defines the skeleton of an algorithm as an
abstract class, allowing its subclasses to provide concrete behavior.

The template method is used in
frameworks, where each implements the invariant parts of a domain's
architecture, leaving "placeholders" for customisation options. This
is an example forinversion of control, also called theHollywood principle. Reasons to use the template
method are to:[4]

·Avoid duplication in the code: the general workflow structure is
implemented once in the abstract class'salgorithm, and
necessary variations are implemented in each of the subclasses.

·Control at what point(s)subclassingis allowed. As opposed to a simple
polymorphic override, where the base method would be entirely rewritten
allowing radical change to the workflow, only the specific details of the
workflow are allowed to change.

The control structure (inversion of control) that is the result of the
application of a template pattern is often referred to as the Hollywood
Principle: "Don't call us, we'll call you." Using this principle, the
template method in a parent class controls the overall process by calling
subclass methods as required.

import java.util.Random;

/**

* An abstract class
that is common to several games in which players play

* against the others,
but only one is playing at a given time.

*/

abstractclassGame {

protectedintplayersCount;

abstractvoid initializeGame();

abstractvoid makePlay(int player);

abstractboolean endOfGame();

abstractvoid printWinner();

/* A template method : */

publicfinalvoid playOneGame(int playersCount) {

this.playersCount = playersCount;

initializeGame();

int j = 0;

while (!endOfGame()) {

makePlay(j);

j
= (j + 1) % playersCount;

}

printWinner();

}

}

// Now we can extend this class in order

// to implement actual games:

class Monopoly extendsGame {

privateintcurrentPlayer;

/* Implementation of necessary concrete methods */

void initializeGame() {

// Initialize players

// Initialize money

}

void makePlay(int player) {

// Process one turn of player

System.out.println("Playing player: " +
player);

this.currentPlayer = player;

}

boolean endOfGame() {

// Return true if game is over

// according to Monopoly rules

Random
rand = new Random();

return rand.nextInt(100) < 5 ? true : false;

}

void printWinner() {

// Display who won

System.out.println("Winner of Monopoly game is player: "

+
currentPlayer);

}

/* Specific declarations for the Monopoly game. */

// ...

}

class Chess extendsGame {

privateintcurrentPlayer;

/* Implementation of necessary concrete methods */

void initializeGame() {

// Initialize players

// Put the pieces on the board

}

void makePlay(int player) {

// Process a turn for the player

System.out.println("Playing player: " +
player);

this.currentPlayer = player;

}

boolean endOfGame() {

// Return true if in Checkmate or

// Stalemate has been reached

Random
rand = new Random();

return rand.nextInt(100) < 10 ? true : false;

}

void printWinner() {

System.out.println("Winner of Chess game is player: " + currentPlayer);

}

/* Specific declarations for the chess game. */

// ...

}

publicclass TemplateMethodExample {

publicstaticvoid main(String[] args) {

Game g1 = new Chess();

g1.playOneGame(2);

Monopoly
m1 = new Monopoly();

m1.playOneGame(4);

}

}

Template method(recognizeable by behavioral methods which already have a
"default" behaviour definied by an abstract type)

·javax.servlet.http.HttpServlet, all
the doXXX() methods by default sends
a HTTP 405 "Method Not Allowed" error to the response. You're free to
implement none or any of them.

11.Visitor - separates
an algorithm from an object structure by moving the hierarchy of methods into
one object.

In the example below, every car element has
to do perform same algorithm (print and do, but in their own way) so we can
take out the algorithms into their own classes and invoke them when the
corresponding visit method is called. In future more algorithms may be added to
all car elements as a new class extending CarElementVisitor.

* known at compile time to be a Wheel.
Moreover, each implementation of

* ICarElementVisitor implements the
visit(Wheel), which is another

* decision that is made at run time. This
can be considered the second

* dispatch.

*/

visitor.visit(this);

}

}

class Engine implements ICarElement {

publicvoid accept(ICarElementVisitor
visitor) {

visitor.visit(this);

}

}

class Body implements ICarElement {

publicvoid accept(ICarElementVisitor
visitor) {

visitor.visit(this);

}

}

class Car implements ICarElement {

ICarElement[] elements;

public Car() {

// create new Array of elements

this.elements = new ICarElement[] { new Wheel("front left"),

new Wheel("front right"), new Wheel("back left"),

new Wheel("back right"), new Body(), new Engine() };

}

publicvoid accept(ICarElementVisitor
visitor) {

for (ICarElement elem : elements) {

elem.accept(visitor);

}

visitor.visit(this);

}

}

class CarElementPrintVisitor implements ICarElementVisitor {

publicvoid visit(Wheel wheel) {

System.out.println("Visiting " +
wheel.getName() + " wheel");

}

publicvoid visit(Engine engine) {

System.out.println("Visiting engine");

}

publicvoid visit(Body body) {

System.out.println("Visiting body");

}

publicvoid visit(Car car) {

System.out.println("Visiting car");

}

}

class CarElementDoVisitor implements ICarElementVisitor {

publicvoid visit(Wheel wheel) {

System.out.println("Kicking my " +
wheel.getName() + " wheel");

}

publicvoid visit(Engine engine) {

System.out.println("Starting my engine");

}

publicvoid visit(Body body) {

System.out.println("Moving my body");

}

publicvoid visit(Car car) {

System.out.println("Starting my car");

}

}

publicclass VisitorExample {

publicstaticvoid main(String[] args) {

ICarElement
car = new Car();

car.accept(new CarElementPrintVisitor());

car.accept(new CarElementDoVisitor());

}

}

Visitor(recognizeable by two different abstract/interface
types which has methods definied which takes each the other abstract/interface type; the
one actually calls the method of the other and the other executes the desired
strategy on it)