UP | HOME

装饰器模式

Table of Contents

装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例

UML

decorator.png

Java

  • 定义接口Sourceable:
    public interface Sourceable {
        void method();
    }
    
  • Source实现Sourceable作为被装饰类:
    public class Source implements Sourceable {
        public void method() {
            System.out.println("the original method!");
        }
    }
    
  • Decorator类是一个装饰类,可以为Source类动态的添加一些功能:
    public class Decorator implements Sourceable {
    
        private Sourceable source;
    
        public Decorator(Sourceable source) {
            super();
            this.source = source;
        }
    
        public void method() {
            System.out.println("before decorator!");
            source.method();
            System.out.println("after decorator!");
        }
    
    }
    
  • 测试类:
    public class DecoratorTest {
        public static void main(String[] args) {
            Sourceable source = new Source();
            Sourceable obj = new Decorator(source);
            obj.method();
        }
    }
    
  • 测试结果:
    before decorator!
    the original method!
    after decorator!
    

Scheme

使用高阶函数来增加动态功能:

(define method
  (lambda ()
    (begin 
      (display "the original method!")
      (newline)
      #t)))

(define decorator
  (lambda (fn)
    (begin
      (display "before decorator!")
      (newline)
      (fn)
      (display "after decorator!")
      (newline)
      #t)))

测试:

(decorator method)

;; 1 ]=> before decorator!
;; the original method!
;; after decorator!

;;Value: #t

Next:代理模式

Previous:适配器模式

Home:目录