In the decorator template, I am confused about how to use the decorator method. I found out that the decorator pattern is used to add functions to the base class. But I could only name the external decorator method, so how to use the internal decorator method if it is not mentioned in the interface. I am not good at English, so I write code to demonstrate my question.
public class OrderSystem {
public static void main(String[] args) {
Pancakes pancakes = new MixedPancakes();
pancakes = new Ham(pancakes);
((Ham) pancakes).hamState();
pancakes = new Egg(pancakes);
((Egg) pancakes).eggState();
Pancakes pancakes1 = new Ham(new Egg(new FlourPancakes()));
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;
}
}
, , , (, cost() getDescription()), . , , , shoot() - . , shoot(), cut() - . ?
.