BehavioralDesignPattern - Tagged
BehavioralDesignPattern - Tagged
@Override
@Override
protected void write(String message) {
protected void write(String message) {
[Link]("Error Console::Logger: " + message);
[Link]("Standard Console::Logger: " + message);
}
}
}
}
@Override [Link](fileLogger);
protected void write(String message) { [Link](consoleLogger);
[Link]("File::Logger: " + message);
} [Link]([Link], "This is an information.");
}
}
Chain Of Responsibility Design Pattern
Output:
• Applicability:
Standard Console::Logger: This is an information.
------------------ • More than one object may handle a request, and the handler isn't
File::Logger: This is a debug level information.
Standard Console::Logger: This is a debug level information.
known a priori. The handler should be ascertained automatically
------------------
Error Console::Logger: This is an error level information. • You want to issue a request to one of several objects without
File::Logger: This is an error level information.
specifying the receiver explicitly
Standard Console::Logger: This is an error level information.
• Reduced coupling. The pattern frees an object from knowing which • A request is wrapped under an object as command and passed to
other object handles a request invoker object. Invoker object looks for the appropriate object which
can handle this command and passes the command to the
corresponding object which executes it.
• Added flexibility in assigning responsibilities to objects. Chain of
Responsibility gives you added flexibility in distributing
• An object is used to represent and encapsulate all information
responsibilities among objects
needed to call a method at a later time
Receiver
Invoker
Command
[Link](buyStockOrder);
[Link](sellStockOrder);
}
}
public interface Order {
Command Design Pattern public void execute();
public void undo();
}
• Applicability and consequences:
• It's easy to add new Commands, because you don't have to public BuyStock(Stock abcStock){
[Link] = abcStock; }
change existing classes
import [Link];
public class SellStock implements Order { import [Link];
}
public class Stock { public class CommandPatternDemo {
private String name = "ABC";
private int quantity = 10; public static void main(String[] args) {
[Link](buyStockOrder);
[Link](sellStockOrder);
}
}
@Override
public String next() {
if([Link]()){
return names[index++]; }
return null;}
}
public interface Container { public class Client {
public void setName(String name) { public static void showMessage(User user, String message){
[Link] = name;}
[Link](new Date().toString() + " [" + [Link]() + "] : " +
public User(String name){ message);
[Link] = name;} }
}
public void sendMessage(String message){
[Link](this,message);}
}
Output:
public class Client {
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!
Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!
public static void main(String[] args) {
[Link]("Hi! John!");
[Link]("Hello! Robert!");
}
}
Mediator Design Pattern Mediator Design Pattern
• Applicability • Consequences
• A set of objects communicate in well-defined but complex ways. • A mediator promotes loose coupling between colleagues. You can
The resulting interdependencies are unstructured and difficult to vary and reuse Colleague and Mediator classes independently
understand
//save to memento
//undo
From Originator: Current Version of Article From Originator: Previous Article Saved in Memento
Article 1: I walked. Article 2: I walked in the street.
Save Files 2
From Originator: Saving to Memento Current Article 1
Save Files 1
Current Article 1 //undo
//------------------- From Originator: Previous Article Saved in Memento
Article 1: I walked.
From Originator: Current Version of Article
Article 2: I walked in the street. Save Files 2
Current Article 0
From Originator: Saving to Memento
Save Files 2 //redo
Current Article 2 From Originator: Previous Article Saved in Memento
//--------------------- Article 2: I walked in the street.
Save Files 2
Current Article 1
Memento Design pattern Memento Design pattern
• Applicability • Consequences
• An object's state must be saved so that it can be restored to that • Memento avoids exposing information that only an originator should
state later, and manage but that must be stored nevertheless outside the originator
• A direct interface to obtaining the state would expose • It simplifies Originator. In other encapsulation-preserving designs,
implementation details and break the object’s encapsulation. Originator keeps the versions of internal state that clients have
requested. That puts all the storage management burden on
Originator
import [Link];
import [Link]; public abstract class Observer {
protected Subject subject;
public class Subject { public abstract void update();
}
private List<Observer> observers = new ArrayList<Observer>();
private int state;
public int getState() { return state; } public class BinaryObserver extends Observer{
@Override @Override
public void update() { public void update() {
[Link]( "Octal String: ” + [Link]( "Hex String: ” +
[Link]( [Link]() ) ); [Link]( [Link]() ).toUpperCase() );
} }
} }
• When a change to one object requires changing others, and you • Abstract coupling between Subject and Observer. All a subject knows
don't know how many objects need to be changed is that it has a list of observers. The subject doesn't know the
concrete class of any observer. Thus the coupling between subjects
and observers is abstract and minimal
• When an object should be able to notify other objects without
making assumptions about who these objects are. In other words,
you don't want these objects tightly coupled. • Support for broadcast communication. The notification is broadcast
automatically to all interested objects that subscribed to it
public Context(){
state = null;}
• An object's behavior depends on its state, and it must change its • Define a family of algorithms or strategies, encapsulate each one,
behavior at run-time depending on that state. and make them interchangeable.
• Operations have large, multipart conditional statements that • A class strategy or its algorithm can be changed at run time
depend on the object's state. The State pattern puts each branch of
the conditional in a separate class. This lets you treat the object's
• Strategy lets the algorithm vary independently from clients that use
state as an object in its own right that can vary independently from
it
other objects
Strategy Design Pattern Strategy Design Pattern
• Structure • Example
@Override
public int doOperation(int num1, int num2) { public class OperationMultiply implements Strategy{
return num1 + num2;
} @Override
} public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
public class StrategyPatternDemo {
public class Context {
public static void main(String[] args) {
private Strategy strategy;
Context context = new Context(new OperationAdd());
public Context(Strategy strategy){ [Link]("10 + 5 = " + [Link](10, 5));
[Link] = strategy;
} context = new Context(new OperationSubstract());
[Link]("10 - 5 = " + [Link](10, 5));
public int executeStrategy(int num1, int num2){
return [Link](num1, num2); context = new Context(new OperationMultiply());
} [Link]("10 * 5 = " + [Link](10, 5));
} }
}
10 + 5 = 15
• many related classes differ only in their behavior. Strategies
10 - 5 = 5
10 * 5 = 50 provide a way to configure a class with one of many behaviors
• An algorithm uses data that clients shouldn't know about. Use the
Strategy pattern to avoid exposing complex, algorithm-specific data
structures.
Strategy Design Pattern Template Design Pattern
• Consequences • Intent
• Strategies eliminate conditional statements • Template Method lets subclasses redefine certain steps of an
algorithm without changing the algorithm's structure
• A choice of implementations. Strategies can provide different
implementations of the same behavior • An abstract class defines template(s) to execute its methods. Its
subclasses can override the method implementation.
• Clients must be aware of different Strategies. The pattern has a
potential drawback in that a client must understand how Strategies
differ before it can select the appropriate one
@Override Output:
void startPlay() {
[Link]("Football Game Started. Enjoy Cricket Game Initialized! Start playing.
the game!"); Cricket Game Started. Enjoy the game!
} Cricket Game Finished!
} Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!
Template Design Pattern Visitor Design Pattern
• Applicability • Intent
• To implement the invariant parts of an algorithm once and leave it • Represent an operation to be performed on the elements of an
up to subclasses to implement the behavior that can vary object structure.
• When common behavior among subclasses should be factored • Visitor lets you define a new operation without changing the
and localized in a common class to avoid code duplication classes of the elements on which it operates.
Concert element
Visitor Interface
public class Computer implements ComputerPart {
public interface ComputerPartVisitor {
ComputerPart[] parts; Visit operation for each concrete class from
public void visit(Computer computer); the element structure
@Override }
public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < [Link]; i++) {
parts[i].accept(computerPartVisitor);
}
[Link](this);
}
}
public class VisitorPatternDemo {
public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
public static void main(String[] args) {
@Override
public void visit(Computer computer) {
ComputerPart computer = new Computer(); Object of element
[Link]("Displaying Computer.");
} Call accept method from the concert element class ComputerPart
[Link](new ComputerPartDisplayVisitor());
@Override
Create object of Visitor Class
public void visit(Mouse mouse) {
}
[Link]("Displaying Mouse.");
}
}
@Override
public void visit(Keyboard keyboard) { Output:
[Link]("Displaying Keyboard.");
} Displaying Mouse.
Displaying Keyboard.
@Override Displaying Monitor.
public void visit(Monitor monitor) { Displaying Computer.
[Link]("Displaying Monitor.");
}
}
@Override
public String interpret(InterpreterContext ic) {
return [Link](this.i);
}
}
public class InterpreterClient {
public class IntToHexExpression implements Expression { public InterpreterContext ic;
Output:
28 in Binary= 11100
28 in Hexadecimal= 1c