Monday, March 14, 2011

Decorator Design Pattern

මෙහිදී සිදු කරන්නේ ප්‍රධාන වශයෙන් වන එක object එකක් නිර්මාණය කර, එයට වෙනස් වෙනස් දේ එක්කර modify කරන අවස්ථා විදහා පෑම සඳහා "decorator" objects නිර්මාණය කිරීමයි.

උදාහරණයක් ලෙස කොත්තුවක් පිලියෙල කිරීමේ අවස්ථාව සලකා බලමු.

මෙහිදී රොටී කොත්තුවක් පිලියෙල කිරීම මූලික පියවරයි.

එයට එක්කර "decorate" කලහැකි දේවල් ලෙස chicken, fish, cheese,egg සඳහන් කල හැක.

cheese සහ chicken යෙදූ රොටී කොත්තුවක මිල ගණනය කිරීම සඳහා java program එකක් ලිවීමට අවශ්‍ය යැයි සිතමු.

මුලින්ම රොටී object එකක් සාදා ගත යුතුය.

ඕනෑම කෑම වර්ගයක් සඳහා වන Meal class එක සාදා ගනිමු.

public abstract class Meal {
String Description="unknown meal";
public String getDescription(){
return Description;
}
public abstract double cost();
}


එහි sub class එකක් ලෙස RottyKottu class එක සාදා ගනිමු.

public class RottyKottu extends Meal{
public RottyKottu(){
Description="RottyKottu";
}
public double cost(){
return 100;
}
}

ඊලඟ පියවර වන්නේ decorators (cheese සහ chicken objects) සාදා ගැනීමයි. මේ සඳහා අපට මුලින්ම CondimentDecorator abstract class එක ලියා ගැනීමට සිදුවේ.


public abstract class CondimentDecorator extends Meal {
public abstract String getDescription();
}


දැන් chicken සහ cheese decorator objects සාදා ගනිමු.


1. public class Chicken extends CondimentDecorator {
Meal meal;
public Chicken (Meal meal){
this.meal=meal;
}
public String getDescription(){
return meal.getDescription()+",Chicken";}
public double cost(){
return 25.00+ meal.cost();
}
}

2. public class Cheese extends CondimentDecorator{
Meal meal;
public Cheese (Meal meal){
this.meal=meal;
}
public String getDescription(){
return meal.getDescription()+",Cheese";}
public double cost(){
return 35.00+ meal.cost();
}
}

දැන් ඇත්තේ අවසාන පියවරයි. එනම් cheese සහ chicken යෙදූ කොත්තුවක මිල ගණනය කිරීම සඳහා program එක ලිවීමයි.

public class kottu1 {
public static void main(String[] args) {
Meal m1 = new RottyKottu();
System.out.println(m1.getDescription()+"Rs"+m1.cost());
m1=new Cheese(m1);    //m1 gets decorated by cheese
m1=new Chicken(m1);  //m1 gets decorated by chiken
System.out.println(m1.getDescription()+"Rs"+m1.cost());

}
}

No comments:

Post a Comment