Roti Telur, anyone ?
Wednesday, January 04, 2006 | rizan
Assalamu'alaikum,
Disebabkan first post cerita psl mamak, so kita ambik contoh makanan yg mamak buat, Roti Canai. Memang roti canai ni takkan terdapat di mana2 dlm dunia ni kecuali Malaysia. Originated from Malaysia. Berkat hasil usaha org kita (especially mamak) dlm menghasilkan variety roti canai, terhasillah contoh ni.
abstract class Roti {
String description = "Unknown Roti"; //tak tau lagi roti apa ni...
public String getDescription() {
return description;
}
public abstract double cost();
}
class RotiKosong extends Roti {
public RotiKosong() {
description = "Roti";
}
public double cost() {
return 0.5;
}
}
abstract class RasaDecorator extends Roti {
public abstract String getDescription();
}
class Telur extends RasaDecorator {
Roti roti;
public Telur(Roti roti) {
this.roti = roti;
}
public String getDescription() {
return roti.getDescription() + " Telur";
}
public double cost() {
return .30 + roti.cost();
}
}
class Bawang extends RasaDecorator {
Roti roti;
public Bawang(Roti roti) {
this.roti = roti;
}
public String getDescription() {
return roti.getDescription() + " Bawang";
}
public double cost() {
return .20 + roti.cost();
}
}
class Planta extends RasaDecorator {
Roti roti;
public Planta(Roti roti) {
this.roti = roti;
}
public String getDescription() {
return roti.getDescription() + " Planta";
}
public double cost() {
return .30 + roti.cost();
}
}
class Pisang extends RasaDecorator {
Roti roti;
public Pisang(Roti roti) {
this.roti = roti;
}
public String getDescription() {
return roti.getDescription() + " Pisang";
}
public double cost() {
return .40 + roti.cost();
}
}
public class RotiDemo {
public static void main(String[] args) {
//roti telur saja
Roti roti = new RotiKosong();
roti = new Telur(roti);
System.out.println(roti.getDescription()
+ " RM" + roti.cost());
//my favourite, roti pisang
roti = new RotiKosong();
roti = new Pisang(roti);
System.out.println(roti.getDescription()
+ " RM" + roti.cost());
//roti telur campur bawang goreng dgn planta :-)
roti = new RotiKosong();
roti = new Bawang(roti);
roti = new Telur(roti);
roti = new Planta(roti); //goreng dgn planta
System.out.println(roti.getDescription()
+ " RM " + roti.cost());
}
}
Contoh ni menggunakan Decorator Pattern, kalau ikut Huston,
"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."
Senang cerita, kita menggunakan decorator utk menambah sifat kepada sesuatu object (secara dinamik). Kalau ikut contoh di atas, cost adalah bergantung kpd setiap bahan yg digunakan. Maknanya, kalau kita ada tambahan bahan nak bg sedap lg roti, kita boleh tambah lg dan cost overall roti bertambah automatically. Kalau harga bahan2 naik, cthnya pisang, kita hanya ubah Pisang saja.
Demikianlah adanya.
0 Responses to "Roti Telur, anyone ?"
Post a Comment