0% found this document useful (0 votes)
5 views30 pages

BehavioralDesignPattern - Tagged

The document provides an overview of behavioral design patterns in software development, focusing on their role in managing algorithms and responsibilities between objects. It details specific patterns such as Chain of Responsibility, Command, Iterator, Mediator, and Memento, including their intents, structures, and examples. Each pattern is discussed in terms of its applicability, consequences, and how it promotes loose coupling and flexibility in code design.

Uploaded by

loy242424
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views30 pages

BehavioralDesignPattern - Tagged

The document provides an overview of behavioral design patterns in software development, focusing on their role in managing algorithms and responsibilities between objects. It details specific patterns such as Chain of Responsibility, Command, Iterator, Mediator, and Memento, including their intents, structures, and examples. Each pattern is discussed in terms of its applicability, consequences, and how it promotes loose coupling and flexibility in code design.

Uploaded by

loy242424
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Behavioral Design Patterns

• Behavioral patterns are concerned with algorithms and


BEHAVIORAL DESIGN the assignment of responsibilities between objects

PATTERNS • Behavioral patterns describe not just patterns of objects or


classes but also the patterns of communication between
Software Design Patterns
them
CPIT-251

• Behavioral class patterns use inheritance and object


composition to distribute behavior between classes

• Provide loose coupling between objects, and maintain


dependencies between objects

Behavioral Design Patterns Chain Of Responsibility Design Pattern


• Chain of Responsibility • Intent
• Command
• Interpreter • Avoid coupling the sender of a request to its receiver by giving
more than one object a chance to handle the request
• Iterator
• Mediator
• Chain the receiving objects and pass the request along the chain
• Memento
until an object handles it
• Observer
• State
• Strategy
• Template Method
• Visitor
Chain Of Responsibility Design Pattern Chain Of Responsibility Design Pattern
• Motivation • Structure

public abstract class AbstractLogger {

Chain Of Responsibility Design Pattern public static int INFO = 1;


public static int DEBUG = 2;
• Example public static int ERROR = 3;
protected int level;

protected AbstractLogger nextLogger; Next element in chain or responsibility

public void setNextLogger(AbstractLogger nextLogger){


[Link] = nextLogger; }
Info message -> Console Logger
Debug Message -> File Logger
Error Message -> Error Logger public void logMessage(int level, String message){
if([Link] <= level){
write(message); }
if(nextLogger !=null){
[Link](level, message); }
}

abstract protected void write(String message);


}
public class ErrorLogger extends AbstractLogger {
public class ConsoleLogger extends AbstractLogger {
public ErrorLogger(int level){
public ConsoleLogger(int level){
[Link] = level; }
[Link] = level; }

@Override
@Override
protected void write(String message) {
protected void write(String message) {
[Link]("Error Console::Logger: " + message);
[Link]("Standard Console::Logger: " + message);
}
}
}
}

public class Client {


Info message -> Console Logger
Debug Message -> File Logger
public static void main(String[] args){ Error Message -> Error Logger
public class FileLogger extends AbstractLogger {
AbstractLogger errorLogger = new ErrorLogger([Link]);
public FileLogger(int level){ AbstractLogger fileLogger = new FileLogger([Link]);
[Link] = level; AbstractLogger consoleLogger = new
} ConsoleLogger([Link]);
Error Logger (level 3) -> File Logger (level 2) -> Console Logger (level 1)

@Override [Link](fileLogger);
protected void write(String message) { [Link](consoleLogger);
[Link]("File::Logger: " + message);
} [Link]([Link], "This is an information.");

} [Link]([Link], "This is a debug level


information.");

[Link]([Link], "This is an error level


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.

• The set of objects that can handle a request should be specified


dynamically.

Chain Of Responsibility Design Pattern Command Design Pattern


• Consequences: • Intent

• 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

• Support undoable operations


Command Design Pattern Command Design Pattern
• Structure • Example

Receiver

Invoker
Command

public interface Order {


void execute(); public class SellStock implements Order {
}
private Stock abcStock;

public SellStock(Stock abcStock){


public class BuyStock implements Order {
[Link] = abcStock; }
private Stock abcStock;
public void execute() {
public BuyStock(Stock abcStock){
[Link](); }
[Link] = abcStock; }
}
public void execute() {
[Link](); }
}
import [Link];
public class Stock {
import [Link];
private String name = "ABC";
private int quantity = 10;
public class Broker {
public void buy(){
public void placeOrders(Order order){
[Link]("Stock [ Name: "+name+", Quantity: " +
[Link]();
quantity +" ] bought");
}
}
}
public void sell(){
[Link]("Stock [ Name: "+name+", Quantity: " +
quantity +" ] sold");
}
}

public class CommandPatternDemo {

public static void main(String[] args) {


Output:
Stock abcStock = new Stock();
Stock [ Name: ABC, Quantity: 10 ] bought
BuyStock buyStockOrder = new BuyStock(abcStock);
Stock [ Name: ABC, Quantity: 10 ] sold
SellStock sellStockOrder = new SellStock(abcStock);

Broker broker = new Broker();

[Link](buyStockOrder);

[Link](sellStockOrder);
}
}
public interface Order {
Command Design Pattern public void execute();
public void undo();
}
• Applicability and consequences:

public class BuyStock implements Order {


• Command decouples the object that invokes the operation from the
one that knows how to perform it private Stock abcStock;

• It's easy to add new Commands, because you don't have to public BuyStock(Stock abcStock){
[Link] = abcStock; }
change existing classes

public void execute() {


• Support undo operations
[Link](); }

public void undo() {


[Link]();
}
}

import [Link];
public class SellStock implements Order { import [Link];

private Stock abcStock; public class Broker {

public SellStock(Stock abcStock){ public void placeOrders(Order order){


[Link] = abcStock; } [Link]();
}

public void execute() { public void undoOrders(Order order){


[Link](); } [Link]();
}
public void undo() {
[Link](); }
}

}
public class Stock { public class CommandPatternDemo {
private String name = "ABC";
private int quantity = 10; public static void main(String[] args) {

public void buy(){ Stock abcStock = new Stock();


[Link]("Stock [ Name: "+name+", Quantity: " +
quantity +" ] bought"); BuyStock buyStockOrder = new BuyStock(abcStock);
}
SellStock sellStockOrder = new SellStock(abcStock);
public void sell(){
[Link]("Stock [ Name: "+name+", Quantity: " + Broker broker = new Broker();
quantity +" ] sold");
} [Link](buyStockOrder);
}
[Link](sellStockOrder);

[Link](buyStockOrder);

[Link](sellStockOrder);
}
}

Iterator Design Pattern Iterator Design Pattern


• Intent: • Motivation

• Provide a way to access the elements of collections sequentially


without exposing its underlying representation
Iterator Design Pattern Iterator Design Pattern
• Structure • Example

public class NameIterator implements Iterator {


public interface Iterator {
String names[];
public boolean hasNext();
int index;
public String next();
public NameIterator(String[] newName){
[Link] = newName;}
}
@Override
public boolean hasNext() {
if(index <[Link]){
return true;}
return false;}

@Override
public String next() {
if([Link]()){
return names[index++]; }
return null;}
}
public interface Container { public class Client {

public Iterator getIterator(); public static void main(String[] args) {

} NameRepository namesRepository = new NameRepository();

Iterator iter = [Link]();


public class NameRepository implements Container {
while ([Link]()){
String name = (String)[Link]();
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
[Link]("Name : " + name);
}
@Override
}
public Iterator getIterator() {
}
return new NameIterator(names);
}

Iterator Design Pattern


Output
• Applicability and Consequences
Name : Robert
Name : John • To access an aggregate object's contents without exposing its
Name : Julie
Name : Lora
internal representation.

• To support multiple traversals of aggregate objects by providing a


uniform interface for traversing different aggregate structures
Mediator Design Pattern Mediator Design Pattern
• Intent • Motivation

• This pattern provides a mediator class which normally handles all


the communications between different classes and supports easy
maintenance of the code by loose coupling

Mediator Design Pattern Mediator Design Pattern


• Structure • Example
public class User {

private String name;


import [Link];
public String getName() {
return name; } public class ChatRoom {

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) {

User robert = new User("Robert");


User john = new User("John");

[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

• A mediator replaces many-to-many interactions with one-to-many


• Reusing an object is difficult because it refers to and interactions between the mediator and its colleagues. One-to-many
communicates with many other objects relationships are easier to understand, maintain, and extend

• The Mediator pattern trades complexity of interaction for complexity


in the mediator. This can make the mediator itself a monolith that's
hard to maintain.

Memento Design pattern Memento Design pattern


• Intent • Structure

• A way to store object’s previous state so the object can be restored


to its state later
public class Originator {

private String article;


public class Memento { Sets the value for the article
public void set(String newArticle) {
[Link]("From Originator: Current Version of Article
private String article; The article stored in memento Object
\n"+newArticle+ "\n");
[Link] = newArticle; }
Save a new article String to the memento Object
public Memento(String articleSave) { article = articleSave; } Creates a new Memento with a new article
public Memento storeInMemento() {
[Link]("From Originator: Saving to Memento");
public String getSavedArticle() { return article; } return new Memento(article);
}
Return the value stored in article
} Gets the article currently stored in memento

public String restoreFromMemento(Memento memento) {


article = [Link]();
[Link]("\n From Originator: Previous Article Saved in
Memento\n"+article + "\n");
return article;
}
}

public class Client {


public static void main(String[] args) {

import [Link]; int saveFiles = 0, currentArticle = 0;


String theArticle;
public class CareTaker {
Where all mementos are saved
CareTaker caretaker = new CareTaker();
ArrayList<Memento> savedArticles = new ArrayList<Memento>(); Originator originator = new Originator();
Adds memento to the ArrayList
[Link]("Article 1: I walked. ");
public void addMemento(Memento m) { [Link](m); } [Link]( [Link]() );
saveFiles++;
Gets the memento requested from the ArrayList currentArticle++;
public Memento getMemento(int index) { [Link]("Save Files " + saveFiles);
return [Link](index); } [Link]("Current Article " + currentArticle);

} [Link]("Article 2: I walked in the street. ");


[Link]( [Link]() );
saveFiles++;
currentArticle++;
[Link]("Save Files " + saveFiles);
[Link]("Current Article " + currentArticle);
if (currentArticle >= 1){
currentArticle--; if ((saveFiles - 1) > currentArticle){
theArticle=
[Link]([Link](currentArticle)); currentArticle++;
[Link]("Save Files " + saveFiles); theArticle =
[Link]("Current Article " + currentArticle); [Link]( [Link](currentArticle) );
} [Link]("Save Files " + saveFiles);
else [Link]("Current Article " + currentArticle);
[Link]("\n There are no more saved articles."); }
}
}
if (currentArticle >= 1){
currentArticle--;
theArticle=
[Link]([Link](currentArticle));
[Link]("Save Files " + saveFiles);
[Link]("Current Article " + currentArticle);
}
else
[Link]("\n There are no more saved articles.");

//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

• Mementos might incur considerable overhead if Originator must copy


large amounts of information to store in the memento or if clients
create and return mementos to the originator often enough

Observer Design Pattern Observer Design Pattern


• Intent • Motivation

• 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 Observer Design Pattern
• Structure • Example

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{

public void setState(int state) { public BinaryObserver(Subject subject){


[Link] = state; [Link] = subject;
notifyAllObservers(); } [Link](this); }

public void attach(Observer observer){ @Override


[Link](observer); } public void update() {
[Link]( "Binary String: ” +
public void notifyAllObservers(){ [Link]( [Link]() ) );
for (Observer observer : observers) { }
[Link](); } }
}
}
public class OctalObserver extends Observer{ public class HexaObserver extends Observer{

public OctalObserver(Subject subject){ public HexaObserver(Subject subject){


[Link] = subject; [Link] = subject;
[Link](this); } [Link](this); }

@Override @Override
public void update() { public void update() {
[Link]( "Octal String: ” + [Link]( "Hex String: ” +
[Link]( [Link]() ) ); [Link]( [Link]() ).toUpperCase() );
} }
} }

public class ObserverPatternDemo {


Output:
public static void main(String[] args) {
First state change: 15
Subject subject = new Subject(); Hex String: F
Octal String: 17
new HexaObserver(subject); Binary String: 1111
new OctalObserver(subject);
new BinaryObserver(subject); Second state change: 10
Hex String: A
[Link]("First state change: 15"); Octal String: 12
[Link](15); Binary String: 1010

[Link]("Second state change: 10");


[Link](10);
}
}
Observer Design Pattern Observer Design Pattern
• Applicability • Consequences

• 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

• Unexpected updates. Because observers have no knowledge of each


other's presence. Operation on the subject may cause a cascade of
updates to observers and their dependent objects , which can be
hard to track down

State Design Pattern State Design Pattern


• Intent • Motivation

• Allow an object to change its state based on its internal state


State Design Pattern
public class Context {
• Example
private State state;

public Context(){
state = null;}

public void setState(State state){


[Link] = state;}

public State getState(){


return state;}
}

public interface State { public class StartState implements State {


public void doAction(Context context);
} public void doAction(Context context) {

[Link]("Player is in start state");


[Link](this);
}

public class StopState implements State { public String toString(){


return "Start State";
public void doAction(Context context) { }
[Link]("Player is in stop state"); }
[Link](this);
}

public String toString(){


return "Stop State”;
}
}
public class Client {
public static void main(String[] args) {
Output
Context context = new Context(); Player is in start state
Start State
StartState startState = new StartState(); Player is in stop state
[Link](context); Stop State
[Link]([Link]().toString());

StopState stopState = new StopState();


[Link](context);
[Link]([Link]().toString());
}
}

State Design Pattern Strategy Design Pattern


• Applicability • Intent

• 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

public interface Strategy { public class OperationSubstract implements Strategy{


public int doOperation(int num1, int num2);
} @Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
public class OperationAdd implements Strategy{

@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));
} }
}

Strategy Design Pattern


Output • Applicability

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

Template Design Pattern Template Design Pattern


• Structure • Example
public class Cricket extends Game {
public abstract class Game {
@Override
abstract void initialize();
void endPlay() {
abstract void startPlay();
[Link]("Cricket Game Finished!");
abstract void endPlay();
}
Template method should be final to not be changed by subclasses
@Override
public final void play(){ Template method void initialize() {
initialize();
[Link]("Cricket Game Initialized! Start
startPlay();
playing.");
endPlay();
}
}
}
@Override
void startPlay() {
[Link]("Cricket Game Started. Enjoy the
game!");
}
}

public class Football extends Game { public class TemplatePatternDemo {

@Override public static void main(String[] args) {


void endPlay() {
[Link]("Football Game Finished!"); Game game = new Cricket();
} [Link]();
[Link]();
@Override
void initialize() { game = new Football();
[Link]("Football Game Initialized! Start [Link]();
playing."); }
} }

@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.

• To control subclasses extensions. You can define a template


method that calls "hook" operations at specific points, thereby
permitting extensions only at those points.

Visitor Design Pattern Visitor Design Pattern


• Structure • Example
Element Interface Concert element
public interface ComputerPart { public class Monitor implements ComputerPart {

public void accept(ComputerPartVisitor computerPartVisitor); @Override


public void accept(ComputerPartVisitor computerPartVisitor) {
} [Link](this);
}
}
Concert element
public class Keyboard implements ComputerPart {
Concert element
@Override
public void accept(ComputerPartVisitor computerPartVisitor) { public class Mouse implements ComputerPart {
[Link](this);
} @Override
} public void accept(ComputerPartVisitor computerPartVisitor) {
[Link](this);
}
}

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

public Computer(){ public void visit(Mouse mouse);


parts = new ComputerPart[] {new Mouse(), new Keyboard(), public void visit(Keyboard keyboard);
new Monitor()}; } public void visit(Monitor monitor);

@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.");
}
}

Visitor Design Pattern Interpreter Design Pattern


• Consequences • Intent
• Used to defines a grammatical representation for a language and
• Visitor makes adding new operations easy. Visitors make it easy to provides an interpreter to deal with this grammar.
add operations that depend on the components of complex objects
by adding a new visitor • The best example of this pattern is java compiler that interprets the
java source code into byte code that is understandable by JVM.
• Adding new ConcreteElement classes is hard. The Visitor pattern
makes it hard to add new subclasses of Element. Each new • Google Translator is also an example of interpreter pattern where
ConcreteElement required a new abstract operation on Visitor and the input can be in any language and we can get the output
a corresponding implementation in every ConcreteVisitor class interpreted in another language.
Interpreter Design Pattern Interpreter Design Pattern
• Structure • Example

public interface Expression {

String interpret(InterpreterContext ic);


public class InterpreterContext {
}
public String getBinaryFormat(int i){
return [Link](i);
} public class IntToBinaryExpression implements Expression {

public String getHexadecimalFormat(int i){ private int i;


return [Link](i);
} public IntToBinaryExpression(int c){
} this.i=c;
}

@Override
public String interpret(InterpreterContext ic) {
return [Link](this.i);
}

}
public class InterpreterClient {
public class IntToHexExpression implements Expression { public InterpreterContext ic;

private int i; public InterpreterClient(InterpreterContext i){


[Link]=I;}
public IntToHexExpression(int c){
this.i=c; public String interpret(String str){
} Expression exp=null;
if([Link]("Hexadecimal")){
exp= new IntToHexExpression([Link]([Link](0,[Link](” "))));
@Override }else if([Link]("Binary")){
public String interpret(InterpreterContext ic) { exp=new IntToBinaryExpression([Link]([Link](0,[Link](" "))));
return [Link](i); }else return str;
} return [Link](ic);
}
}
public static void main(String args[]){
String str1 = "28 in Binary";
String str2 = "28 in Hexadecimal”;

InterpreterClient ec = new InterpreterClient(new InterpreterContext());


[Link](str1+"= "+[Link](str1));
[Link](str2+"= "+[Link](str2));
}
}

Output:

28 in Binary= 11100
28 in Hexadecimal= 1c

You might also like