设计模式之装饰器模式的学习思考

来源:互联网 发布:网络名词大全 编辑:程序博客网 时间:2024/06/05 16:31

装饰器模式(Decorator Pattern)属于设计模式里的结构型模式一种。

白话地说,我们可以给一个类加一些它没有的功能

比如:给一个圆加上颜色;给手机增加上网的功能等等

它的实现思想:

  • 一般是以抽象类的为装饰类,继承抽象类的子类具体实现装饰内容
  • 组合思想,即被装饰的类的对象作为变量放置在抽象类内部,一般,为了实现给许多具有相同的特质的类统一装饰,我们会用接口来规范被装饰类
  • 这就设计了多态

小例子:

  • 实现给圆和矩形加颜色
  • 圆和矩形可以实现一个接口
  • 抽象装饰类规定装饰的方法,子类具体实现

代码:

interface Shape{    void draw();}class Rectangle implements Shape{   //接口的具体实现类,也是我们要装饰的类    public void draw() {        System.out.println("Shape:Rectangle");    }}class Circle implements Shape{      //同上    public void draw() {        System.out.println("Shape:Circle");    }}abstract class ShapeDecorator implements Shape{ //抽象方法实现接口可以不写接口里的方法    Shape decoratedShape;    public ShapeDecorator(Shape decoratedShape){    //构造方法传递参数,多态、回调的应用        this.decoratedShape=decoratedShape;    }    public void draw(){        decoratedShape.draw();    }}class RedShapeDecorator extends ShapeDecorator{ //子类继承抽象类,如果抽象类有有参数构造方法,子类也有写构造方法    public RedShapeDecorator(Shape decoratedShape) {        super(decoratedShape);    }    public void draw(){     //隔了一个抽象类的接口方法可以不用重写        decoratedShape.draw();        setRedBorder(decoratedShape);    }    private void setRedBorder(Shape decoratedShape) {   //隐藏实现细节        System.out.println("Border Color: Red");    }}public class DecoratorPatternDemo {    public static void main(String[] args) {        Shape circle =new Circle();        Shape redCircle =new RedShapeDecorator(new Circle());        Shape redRectangle =new RedShapeDecorator(new Rectangle());        System.out.println("Circle with normal border");        circle.draw();        System.out.println("\nCircle of red border");        redCircle.draw();        System.out.println("\nRectangle of red border");        redRectangle.draw();    }}

输出:

Circle with normal borderShape:CircleCircle of red borderShape:CircleBorder Color: RedRectangle of red borderShape:RectangleBorder Color: Red

总结:

  • 结构型模式都有组合和多态的思想,即将一个接口型的对象作为属性放置在另一个接口或者抽象类内,通过多态(向上转型)来实现代码复用。
  • 装饰器模式和适配器模式有相同点,也有不同点,要仔细区分
原创粉丝点击