zoukankan      html  css  js  c++  java
  • 装饰器模式

    1.装饰器模式简介

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

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

    2.试验Demo

    interface Shape {
        public void draw();
    }
    
    class Circle implements Shape {
        @Override
        public void draw() {
            System.out.println("Circle: draw(): draw circle");
        }
    }
    
    
    abstract class ShapeDecorator implements Shape { //抽象出的修饰者抽象类
        protected Shape decorator;
        public ShapeDecorator(Shape shape) {
            decorator = shape;
        }
        public void draw() { //若继承者不复写这个方法就还是原有行为。
            decorator.draw();
        }
    }
    
    class RedShapeDecorator extends ShapeDecorator {
        public RedShapeDecorator(Shape shape) {
            super(shape);
        }
    
        public void draw() {
            this.decorator.draw(); //调用原有的行为
            System.out.println("RedShapeDecorator: draw(): add red border"); //添加新的行为
        }
    }
    
    
    public class DecoratorDemo {
        public static void main(String args[]) {
            Shape circle = new Circle();
            Shape redCircle = new RedShapeDecorator(circle);
            
            System.out.println("Normale circle:");
            circle.draw();
    
            System.out.println("Decorated circle:");
            redCircle.draw();
        }
    }

    参考:http://www.runoob.com/design-pattern/decorator-pattern.html

  • 相关阅读:
    HDU 2094 产生冠军
    poj 3269 Building A New Barn
    [js
    有感于NC的强大
    was配置oracle RAC集群的数据源
    vb.net 操作xml
    一个用C++写的Json解析与处理库
    配置apache和nginx的tomcat负载均衡
    Remove Duplicates from Sorted Array [Python]
    LoaderManager使用具体解释(一)---没有Loader之前的世界
  • 原文地址:https://www.cnblogs.com/hellokitty2/p/10715866.html
Copyright © 2011-2022 走看看