Behavior Desgn Patterns
Behavior Desgn Patterns
For our example, we will try to implement a chat application where users can do group chat. Every user will be
identified by it’s name and they can send and receive messages. The message sent by any user should be
received by all the other users in the group.
One of the best real life example is the text editors where we can save it’s data anytime and use undo to restore it to
previous saved state. We will implement the same feature and provide a utility where we can write and save contents to
a File anytime and we can restore it to last saved state. For simplicity, I will not use any IO operations to write data into
file.
Let's imagine a system in which a restaurant needs to record information about the suppliers that bring them
their ingredients. For example, a really high-end restaurant might order directly from a local farm, and the
restaurant needs to keep track of which ingredients come from which suppliers. In our system, we need to
keep track of how much information we enter about a particular supplier, and be able to restore that
information to a previous state if we, say, accidentally enter the wrong address. We can demo this using the
Memento pattern.
class FoodSupplier {
{ Console.WriteLine("\nSaving current state\n");
private string _name; return new FoodSupplierMemento(_name,
private string _phone; _phone, _address);
private string _address; }
public string Name public void RestoreMemento(FoodSupplierMemento
{ memento)
get { return _name; } {
set Console.WriteLine("\nRestoring previous state\n");
{ Name = memento.Name;
_name = value; Phone = memento.PhoneNumber;
Console.WriteLine("Proprietor: " + _name); Address = memento.Address;
} }
} }
public string Phone class FoodSupplierMemento
{ {
get { return _phone; } public string Name { get; set; }
set public string PhoneNumber { get; set; }
{ public string Address { get; set; }
_phone = value;
Console.WriteLine("Phone Number: " + _phone); public FoodSupplierMemento(string name, string
} phone, string address)
} {
public string Address Name = name;
{ PhoneNumber = phone;
get { return _address; } Address = address;
set }
{ }
_address = value; class SupplierMemory
Console.WriteLine("Address: " + _address); {
} private FoodSupplierMemento _memento;
}
public FoodSupplierMemento SaveMemento() public FoodSupplierMemento Memento
{ // Let's store that entry in our database.
set { _memento = value; } SupplierMemory m = new SupplierMemory();
get { return _memento; } m.Memento = s.SaveMemento();
} // Continue changing originator
} s.Address = "548 S Main St. Nowhere, KS";
static void Main(string[] args) // Crap, gotta undo that entry, I entered the wrong
{ address
//Here's a new supplier for our restaurant s.RestoreMemento(m.Memento);
FoodSupplier s = new FoodSupplier(); Console.ReadKey();
s.Name = "Harold Karstark"; }
s.Phone = "(482) 555-1172";
VISITOR
For example, think of a Shopping cart where we can add different type of items (Elements). When we click on checkout
button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move
out this logic to another class using visitor pattern. Let’s implement this in our example of visitor pattern. To implement
visitor pattern, first of all we will create different type of items (Elements) to be used in shopping cart.
Let's create a seperate visitor for each postal region. This way, we can seperate the logic of calculating the total postage
cost from the items themselves. This means that our individual elements don't need to know anything about the postal
cost policy, and therefore, are nicely decoupled from that logic.
Robot - The robot is the context class. It keeps or gets context information such as position, close obstacles, etc, and
passes necessary information to the Strategy class.
In the main section of the application the several robots are created and several different behaviors are created. Each
robot has a different behavior assigned: 'Big Robot' is an aggressive one and attacks any other robot found, 'George
v.2.1' is really scared and run away in the opposite direction when it encounter another robot and 'R2' is pretty calm and
ignore any other robot. At some point the behaviors are changed for each robot.
For our example, we will try to implement a simple Shopping Cart where we have two payment strategies –
using Credit Card or using PayPal. First of all we will create the interface for our strategy pattern example, in
our case to pay the amount passed as argument.
Given any string expression and a token, filter out the information you want. The below is a simple
parser program. the myParser method can be used to parse any expression. The composite, visit and
iterator patterns have been used.
import java.util.*; result =
class Parser{ Arrays.asList(toBeMatched);
private String expression; }
private String token; public List getParseResult() {
private List result; return result;
private String interpreted; }
public void interpret() {
public Parser(String e, String t) { StringBuffer buffer = new StringBuffer();
expression = e; ListIterator list= result.listIterator();
token = t; while (list.hasNext()){
} String token = (String)list.next();
if (token.equals("SFO")){
public void myParser() { token = "San Francisco";
StringTokenizer holder=new }else if(token.equals("CA"))
StringTokenizer(expression, token); {
String[] toBeMatched = new token = "Canada";
String[holder.countTokens()]; }
int idx = 0; //...
while(holder.hasMoreTokens()) { buffer.append(" " + token);
String item = holder.nextToken(); }
int start = item.indexOf(","); interpreted = buffer.toString();
if(start==0) { }
item = item.substring(2); public String getInterpretedResult()
} {
toBeMatched[idx] = item; return interpreted;
idx ++; }
} public static void main(String[] args) {
String source = String result=
"dest='SFO',origin='CA',day='MON'"; parser.getInterpretedResult();
String delimiter = "=,'"; System.out.println(result);
Parser parser = new Parser(source, }
delimiter); }
parser.myParser(); java Parser
parser.interpret(); dest San Francisco origin Canada day MON
CHAIN OF RESPONSIBILITY
Here comes a simple example, just to show how chain of responsibility works. Whenever you
spend company's money, you need get approval from your boss, or your boss's boss. Let's say, the
leadership chain is:
Manager-->Director-->Vice President-->President
The following is a command line program to check who is responsible to approve your expenditure.
import java.io.*; if( successor != null)
abstract class PurchasePower {
successor.processRequest(request);
protected final double base = 500; }
protected PurchasePower successor; }
UnitFactory class contains method called GetUnit which accept one parameter that specify type of unit to create.
This class has one private dictionary of unit types. When new unit is required, the first step is to look into this
dictionary whether this type of unit was created earlier. If yes, program returns reference to this unit. If no, it just
create a new unit and places it into dictionary. You can control the number of instances of each unit type by static
field NumberOfInstances.
Sdc
Create a Question interface that provides the navigation from one question to another or vice-versa.
Create a QuestionManager class that will use Question // this is the BridgePatternDemo class.
interface which will act as a bridge.. public class BridgePatternDemo {
public static void main(String[] args) {
// this is the QuestionManager class. QuestionFormat questions = new
public class QuestionManager { QuestionFormat("Java Programming Language");
protected Question q; questions.q = new JavaQuestions();
public String catalog; questions.delete("what is class?");
questions.display(); questions.displayAll();
questions.newOne("What is inheritance? "); }
}// End of the BridgePatternDemo class.
questions.newOne("How many types of inheritance
are there in java?");
Let´s implement a cake bakery. A colleague of yours wants to open a bakery and asked you to program a
bakery’s software for him. Ingredient is the Part, Recipe is the BuilderContract and Builder is the builder
itself. Cake is the final, customizable product. CakeBuilder is the class which actually creates the product
after customization (after the addition of as many parts – ingredients – as you want). The client would be
the final client or your colleague taking the order.
// 1. EXAMPLE: PART TO CUSTOMIZATE "INGREDIENTS" this.unitPrice = unitPrice;
public interface Ingredient { }
3 // INGREDIENTS WILL HAVE... @Override
4 void printName(); public void printName() {System.out.printf(" Light
String getUnitPrice(); Milk");}
void printCalories(); @Override public String getUnitPrice() {return
} unitPrice;}
public class LightMilk implements Ingredient { @Override public void printCalories()
private int deciLiter; {System.out.printf(" 76kc");}
private int calories; public int getDeciLiter() {return deciLiter;}
private String unitPrice; public void setDeciLiter(int deciLiter) {this.deciLiter =
public LightMilk(int deciLiter){this.deciLiter=deciLiter;} deciLiter;}
public LightMilk(int deciLiter, int calories, String public int getCalories() {return calories;}
unitPrice) { public void setCalories(int calories) {this.calories =
super(); calories;}
this.deciLiter = deciLiter; public void setUnitPrice(String unitPrice)
this.calories = calories; {this.unitPrice = unitPrice;}
} private String unitPrice;
public class Sugar implements Ingredient { public NoSugar(int deciLiter){this.gram=deciLiter;}
private int gram; public NoSugar(int gram, int calories, String unitPrice)
private int calories; {
private String unitPrice; super();
public Sugar(int deciLiter){this.gram=deciLiter;} this.gram = gram;
public Sugar(int gram, int calories, String unitPrice) { this.calories = calories;
super(); this.unitPrice = unitPrice;
this.gram = gram; }
this.calories = calories; @Override public void printName()
this.unitPrice = unitPrice; {System.out.printf(" No Sugar");}
} @Override public String getUnitPrice() {return
@Override public void printName() unitPrice;}
{System.out.printf(" Sugar");} @Override public void printCalories()
@Override public String getUnitPrice() {return {System.out.printf(" 0kc");}
unitPrice;} public int getGram() {return gram;}
@Override public void printCalories() public void setGram(int gram) {this.gram = gram;}
{System.out.printf(" 40kc");} public int getCalories() {return calories;}
public int getGram() {return gram;} public void setCalories(int calories) {this.calories =
public void setGram(int gram) {this.gram = gram;} calories;}
public int getCalories() {return calories;} public void setUnitPrice(String unitPrice)
public void setCalories(int calories) {this.calories = {this.unitPrice = unitPrice;}
calories;} }
public void setUnitPrice(String unitPrice) public class Milk implements Ingredient {
{this.unitPrice = unitPrice;} private int deciLiter;
} private int calories;
public class Choco implements Ingredient { private String unitPrice;
private int gram; public Milk(int deciLiter){this.deciLiter=deciLiter;}
private int calories; public Milk(int deciLiter, int calories, String unitPrice)
private String unitPrice; {
public Choco(int gram, int calories, String unitPrice) { super();
super(); this.deciLiter = deciLiter;
this.gram = gram; this.calories = calories;
this.calories = calories; this.unitPrice = unitPrice;
this.unitPrice = unitPrice; }
} @Override public void printName()
public int getGram() {return gram;} {System.out.printf(" Milk");}
public void setGram(int gram) {this.gram = gram;} @Override public String getUnitPrice() {return
public int getCalories() {return calories;} unitPrice;}
public void setCalories(int calories) {this.calories = @Override public void printCalories()
calories;} {System.out.printf(" 128kc");}
public void setUnitPrice(String unitPrice) public int getDeciLiter() {return deciLiter;}
{this.unitPrice = unitPrice;} public void setDeciLiter(int deciLiter) {this.deciLiter =
@Override public void printName() deciLiter;}
{System.out.printf(" Chocolate");} public int getCalories() {return calories;}
@Override public void printCalories() public void setCalories(int calories) {this.calories =
{System.out.printf(" 389kc");} calories;}
@Override public String getUnitPrice() {return public void setUnitPrice(String unitPrice)
unitPrice;} {this.unitPrice = unitPrice;}
} }
public class NoSugar implements Ingredient { The Builder’s Contract
private int gram; This is the Recipe in our example.
private int calories; // 2. THE BUILDER METHOD WILL ADD
// INGREDIENTS RETURNING THE BUILDER ITSELF // PRINT OUT PART PRICES
public interface Recipe < B > { for (Ingredient ingredient : ingredients) {
B addIngredient(Ingredient ingredient); muffin+=" "+ingredient.getUnitPrice();//NOPMD
} }
// 3. DEFINE THE BUILDER CONTRUCTION METHOD System.out.println(" - Price: "+muffin);
// WHICH BUILDS AND RETURNS THE FINAL PRODUCT }
"T" public void printResult(){
public interface Builder < T > extends Recipe < Builder < System.out.println(" Cake is ready!");
T>>{ }
T build(); }
} Testing it
import java.util.ArrayList; public class Client {
import java.util.List; public static void main(String[] args) {
// 4. IMPLEMENT THE BUILDER ACC. TO YOUR NEEDS Builder < Cake > chocoMuffinBuilder = new
public class CakeBuilder implements Builder < Cake > { CakeBuilder();
// IN THIS CASE THE PARTS ARE THE INGREDIENTS 05
private List < Ingredient > ingredients=new ArrayList < chocoMuffinBuilder.addIngredient(new Choco(10,
Ingredient > ( ); 23, "3.39"));
@Override chocoMuffinBuilder.addIngredient(new Milk(34,
public Cake build() { 67, "1.57"));
if(!ingredients.isEmpty()){ chocoMuffinBuilder.addIngredient(new Sugar(34,
// THE FINAL PRODUCT IS A CHOCO-MUFFIN 67, "2.00"));
return new Cake(ingredients); final Cake chocoMuffin =
} chocoMuffinBuilder.build();
return new Cake(null); chocoMuffin.printResult();
}
@Override }
// BECAUSE I ALWAYS GET A BUILDER BACK, I'M ABLE
TO }
// ADD A LOT OF PARTS BEFORE I CALL "BUILD()"
public Builder < Cake > addIngredient(Ingredient
ingredient) {
if(ingredient!=null){
ingredients.add(ingredient);
}
return this;
}
}
The product
In our example the product to build is a cake.
import java.util.List;
public class Cake {
public Cake(List < Ingredient > ingredients){
String muffin = "";
if(ingredients==null){
System.out.println(" zero cake "+muffin);
return;
}
// PRINT OUT MUFFIN INGREDIENTS
System.out.printf(" Cake with: ");
for (Ingredient ingredient : ingredients) {
ingredient.printName();
}