0
点赞
收藏
分享

微信扫一扫

设计模式之一致性_Decorator装饰器模式_装饰边框和内容的一致性


前言

​​博主github​​

​​博主个人博客http://blog.healerjean.com​​

1、解释

假如现在有一块蛋糕

1、如果只涂上奶油,其他什么都不加,就是奶油蛋糕。

2、如果加上草莓,就是草莓奶油蛋糕。

3、如果再加上一块黑色巧克力板,上面用白色巧克力写上姓名,然后插上代表年龄的蜡烛,就变成了一块生日蛋糕。

像这样不断地为对象添加装饰的设计模式被称为Decorator模式 ,Decorator 指的是装饰。

1.1、适配器模式和装饰器模式的区别

装饰器与适配器都有一个别名叫做 包装模式(Wrapper),它们看似都是起到包装一个类或对象的作用,但是使用它们的目的很不一一样。

适配器模式的意义是要将一个接口转变成另一个接口,它的目的是通过改变接口来达到重复使用的目的。当然也有适配之前的,并且创建跟多的方法。

而装饰器模式不是要改变被装饰对象的接口,而是恰恰要保持原有的接口,但是增强原有对象的功能,或者改变原有对象的处理方式而提升性能。所以这两个模式设计的目的是不同的。

2、实例代码 会发现和适配器模式很像

2.1、功能接口​​ShapeInter​

public interface ShapeInter {

void draw();

}

2.2、功能1 实现类​​RectangleImpl​

public class RectangleImpl implements ShapeInter {

@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}

2.3、功能2 实现类 ​​CircleImpl​

public class CircleImpl implements ShapeInter {

@Override
public void draw() {
System.out.println("Shape: Circle");
}
}

2.4、被装饰的对象

public abstract class AbstractShapeDecorator implements ShapeInter {

protected ShapeInter shapeInter;

public AbstractShapeDecorator(ShapeInter shapeInter) {
this.shapeInter = shapeInter;
}

@Override
public void draw() {
shapeInter.draw();
}
}

2.5、装饰上面的方法

public class RedShapeDecorator extends AbstractShapeDecorator {

public RedShapeDecorator(ShapeInter shapeInter) {
super(shapeInter);
}

@Override
public void draw() {
shapeInter.draw();
ok();
}

private void ok(){
System.out.println("Border Color: Red");
}
}

2.6、测试

package com.hlj.moudle.design.D05_一致性.D12Decorator适配器模式;

/**
* @author HealerJean
* @ClassName Main
* @date 2019/8/14 18:50.
* @Description
*/
public class Main {

public static void main(String[] args) {

ShapeInter circle = new CircleImpl();
System.out.println("Circle with normal border");
circle.draw();


AbstractShapeDecorator redCircle = new RedShapeDecorator(new CircleImpl());
System.out.println("\nCircle of red border");
redCircle.draw();


AbstractShapeDecorator redRectangle = new RedShapeDecorator(new RectangleImpl());
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
}

设计模式之一致性_Decorator装饰器模式_装饰边框和内容的一致性_装饰器模式


举报

相关推荐

0 条评论