简述:
- 学习装饰者模式最大的体验是,对于传统类的功能扩展都是通过继承来实现的,但是这种方式耦合度过高。
- 而装饰者模式在不改变原有的业务类的前提下,更加灵活的扩展业务。
- 类型-结构性
具体代码如下:
(1)普通业务实体类
public class SmallCake extends Cake{
public String describe(){
return "一个小蛋糕";
}
public int price(){
return 10;
}
}
(2)实体类的抽象
public abstract class Cake{
public abstract String describe(){}
public abstract int price(){}
}
(3)抽象装饰类 (关键)
public abstract class DecoratorCake extend Cake{
private Cake cake;
public DecoratorCake(Cake cake){
this.cake = cake;
}
public String describe(){
return this.cake.describe();
}
public int price(){
return this.cake.price;
}
}
(4)具体装饰类
public class AddChocolates extends DecoratorCake{
public AddChocolates(Cake cake){
super(cake);
}
public String describe(){
return super.describe()+"加了巧克力";
}
public int price(){
return super.price+10;
}
}
(5)测试
public class Test{
public static void main(String [] args){
Cake cake = new SmallCake();
cake = new AddChocolates();
}
}
网友评论