zoukankan      html  css  js  c++  java
  • Java设计模式——装饰器模式

    装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构,属于结构型的设计模式。

    意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

    主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

    何时使用:在不想增加很多子类的情况下扩展类。

    优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

    缺点:多层装饰比较复杂。

    注意事项:可代替继承。

    类图:

     

    代码:

    一、建立形状接口

    1 public interface Shape {
    2   void draw();
    3 }

    二、创建两个实现了形状接口的实体类

    1 public class Circle implements Shape {
    2 
    3     @Override
    4     public void draw() {
    5         System.out.println("I am Circle");
    6     }
    7 
    8 }
    public class Rectangle implements Shape {
    
        @Override
        public void draw() {
            System.out.println("I am Rectangle");
        }
    
    }

    三、创建一个实现了形状接口的抽象类——抽象包装类

     1 public abstract class ShapeDecorator implements Shape {
     2   protected Shape inShape;
     3   public ShapeDecorator(Shape inShape){
     4       this.inShape = inShape;
     5   }
     6   
     7   @Override
     8     public void draw() {
     9       inShape.draw();
    10     }
    11 }

    四、创建一个实体类继承包装类,并拓展他的方法

     1 public class RedShapeDecorator extends ShapeDecorator {
     2 
     3     public RedShapeDecorator(Shape inShape) {
     4         super(inShape);
     5     }
     6     
     7     @Override
     8     public void draw() {
     9         inShape.draw();
    10         setRedBorder();
    11     }
    12 
    13     public void setRedBorder(){
    14         System.out.println("Border Color: Red");
    15     }
    16 }

    五、测试

     1 public class DecoratorPatternDemo {
     2     public static void main(String[] args) {
     3         Shape shape1 = new Rectangle();
     4         Shape shape2 = new Circle();
     5         Shape shape1_1 = new RedShapeDecorator(shape1);
     6         Shape shape2_1 = new RedShapeDecorator(shape2);
     7         
     8         shape1.draw();
     9         System.out.println();
    10         shape2.draw();
    11         System.out.println();
    12         shape1_1.draw();
    13         System.out.println();
    14         shape2_1.draw();
    15     }
    16 }
  • 相关阅读:
    Apache Shiro和Spring Security的详细对比
    Oauth2.0 用Spring-security-oauth2 来实现
    引入AOP 报错 error at ::0 formal unbound in pointcut
    日记网站收藏
    Spring 在web 容器中的启动过程
    knockoutjs如何动态加载外部的file作为component中的template数据源
    ORACLE触发器详解
    浅谈数据库分表
    HTTP协议详解(真的很经典)
    ThinkPHP的四种URL模式 URL_MODEL
  • 原文地址:https://www.cnblogs.com/ccw95/p/6015603.html
Copyright © 2011-2022 走看看