in Decorate Pattern ,i'm confuse about how to use decorator method. i have learned that decorate pattern is used add functions to base-class ,but i could call only the outermost decorator's method, so how should i use inner-decorator's method if it not write on interface. i'm not good at English,so i write a code to show my question.
public class OrderSystem {
public static void main(String[] args) {
Pancakes pancakes = new MixedPancakes();
pancakes = new Ham(pancakes);
((Ham) pancakes).hamState(); //call hamState
pancakes = new Egg(pancakes);
((Egg) pancakes).eggState();
//i can't call hamState() there because it not belong to Egg
Pancakes pancakes1 = new Ham(new Egg(new FlourPancakes()));
//similarly, i can't use eggState() there.
System.out.println("订单:" + pancakes1.getDescription());
System.out.println("价格:" + pancakes1.cost());
}
}
interface Pancakes {
public abstract String getDescription();
public abstract int cost();
}
abstract class Seasoning implements Pancakes {
@Override
public abstract String getDescription();
}
class Ham extends Seasoning {
Pancakes pancakes;
public Ham(Pancakes pancakes) {
this.pancakes = pancakes;
}
@Override
public int cost() {
return pancakes.cost() + 2;
}
@Override
public String getDescription() {
return pancakes.getDescription() + "+火腿";
}
public void hamState() {
System.out.println("火腿切碎");
}
}
class Egg extends Seasoning {
Pancakes pancakes;
public Egg(Pancakes pancakes) {
this.pancakes = pancakes;
}
@Override
public int cost() {
return pancakes.cost() + 1;
}
@Override
public String getDescription() {
return pancakes.getDescription() + "+鸡蛋";
}
public void eggState() {
System.out.println("鸡蛋打碎");
}
}
class MixedPancakes implements Pancakes {
@Override
public String getDescription() {
return "五谷杂粮煎饼";
}
@Override
public int cost() {
return 6;
}
}
class FlourPancakes implements Pancakes {
@Override
public String getDescription() {
return "白面煎饼";
}
@Override
public int cost() {
return 5;
}
}
as i asked in annotation ,when a decorator was wrapped by an other, only the method that declared in interface(like cost()
and getDescription()
)will work,and other method won't be called anymore. i thought if i create a soldier, if i use a gun decorate him today, he will be shoot()
--the gun's function. if i decorate him with sword tomorrow, he will not only could shoot()
but also cut()
--the sword's function. can i achieve it with Decorator Pattern? i sorry about any misnomer and thanks for your help.
Aucun commentaire:
Enregistrer un commentaire