1.定义
装饰者模式(Decorator Pattern) 是指在不改变原有对象的基础之上
将功能附加到对象上,提供了比继承更有弹性的替代方案
属于机构型模式
2.适用场景
1.扩展类的功能或者为其附加新的职责
2.动态的给一个对象添加功能,这些功能可以动态的撤销
3.代码
传统继承
image.png
/**
* Description:煎饼
*
* @date 2019-05-28 16:43
*/
public class Pancake {
public String getName(){
return "煎饼";
}
public BigDecimal getPrice(){
return BigDecimal.TEN;
}
}
/**
* Description:鸡蛋煎饼
*
* @date 2019-05-28 16:43
*/
public class EggPancake extends Pancake{
public String getName(){
return "鸡蛋"+super.getName();
}
public BigDecimal getPrice(){
return super.getPrice().add(BigDecimal.valueOf(5L));
}
}
* Description:香肠鸡蛋煎饼
*
* @date 2019-05-28 16:43
*/
public class SausageEggPancake extends EggPancake{
public String getName(){
return "香肠"+super.getName();
}
public BigDecimal getPrice(){
return super.getPrice().add(BigDecimal.valueOf(5L));
}
}
/**
* Description:测试类
*
* @date 2019-05-28 16:54
*/
public class Test {
public static void main(String[] args) {
Pancake pancake = new Pancake();
System.out.println(pancake.getName()+",价格:"+pancake.getPrice());
Pancake eggPancake = new EggPancake();
System.out.println(eggPancake.getName()+",价格:"+eggPancake.getPrice());
Pancake sausageEggPancake = new SausageEggPancake();
System.out.println(sausageEggPancake.getName()+",价格:"+sausageEggPancake.getPrice());
}
}
装饰者模式
image.png
/**
* Description:煎饼
*
* @date 2019-05-28 16:43
*/
public abstract class Pancake {
public abstract String getName();
public abstract BigDecimal getPrice();
}
/**
* Description:普通煎饼
*
* @date 2019-05-28 16:43
*/
public class BasePancake extends Pancake{
@Override
public String getName(){
return "煎饼";
}
@Override
public BigDecimal getPrice(){
return BigDecimal.TEN;
}
}
/**
* Description:煎饼装饰器
*
* @author zhangzhongbo
* @date 2019-05-28 17:05
*/
public abstract class PancakeDecorator extends Pancake{
private Pancake pancake;
public PancakeDecorator(Pancake pancake) {
this.pancake = pancake;
}
@Override
public String getName() {
return pancake.getName();
}
@Override
public BigDecimal getPrice() {
return pancake.getPrice();
}
}
/**
* Description:鸡蛋煎饼装饰器
*
* @date 2019-05-28 17:09
*/
public class EggPancakeDecorator extends PancakeDecorator {
public EggPancakeDecorator(Pancake pancake) {
super(pancake);
}
@Override
public String getName() {
return "鸡蛋"+super.getName();
}
@Override
public BigDecimal getPrice() {
return super.getPrice().add(BigDecimal.valueOf(5L));
}
}
/**
* Description:香肠煎饼装饰器
*
* @date 2019-05-28 17:09
*/
public class SausagePancakeDecorator extends PancakeDecorator {
public SausagePancakeDecorator(Pancake pancake) {
super(pancake);
}
@Override
public String getName() {
return "香肠"+super.getName();
}
@Override
public BigDecimal getPrice() {
return super.getPrice().add(BigDecimal.valueOf(5L));
}
}
和适配器模式的区别
image.png
网友评论