设计模式学习笔记——装饰器模式

来源:互联网 发布:mac安装exe软件 编辑:程序博客网 时间:2024/05/01 02:43

设计模式学习笔记——装饰器模式

装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。

1.实例

把一个形状装饰上不同的颜色,同时又不改变形状类。

//创建形状接口interface Shape{    void show();}//形状实体类class Rectangle implements Shape{    @Override    public void show(){        System.out.println("Shape:Rectangle");    }}class Circle implements Shape{    @Override    public void show(){        System.out.println("Shape:Circle");    }}//装饰抽象类abstract class ColorDecorator implements Shape{    protected Shape sp;    ColorDecorator(Shape sp){        this.sp=sp;    }    public void show(){        sp.show();    }}//装饰类class RedColorDecorator extends ColorDecorator{    RedColorDecorator(Shape sp){        super(sp);    }    @Override    public void show(){        sp.show();        System.out.println("Color:Red");    }}class Solution{    public static void main(String []args){        Circle circle = new Circle();        RedColorDecorator redCircle=new RedColorDecorator(new Circle());        RedColorDecorator redRectangle=new RedColorDecorator(new Rectangle());        circle.show();        redCircle.show();        redRectangle.show();    }}

2.总结

  1. 通常在不想增加太多子类的时候使用装饰器模式扩展类,即替代继承的功能。
  2. 装饰类和被装饰类可以独立发展,不会相互耦合。
  3. 但多层装饰比较复杂。
原创粉丝点击