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

    装饰器[Decorator]模式

    模式定义:在不改变原有对象的基础上,将功能附加到对象上。

    符合开闭原则

    应用场景:扩展一个类的功能或者给一个类添加附加职责

    优点:

    • 1:不改变原有对象的情况下给一个对象添加功能
    • 2: 使用不同的组合可以实现不同的效果
    • 3:符合开闭原则

    java代码:

    public class DecoratorTest {
    
        public static void main(String[] args) {
    
    
            Component component = new ConcreteComponent();
            component.operation();
            System.out.println("------------------------");
            ConcreteDecorator1 concreteDecorator1 = new ConcreteDecorator1(component);
            concreteDecorator1.operation();
            System.out.println("-----------------------");
    
            //test 装饰者2
            ConcreteDecorator2 concreteDecorator2 = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
            concreteDecorator2.operation();
        }
    }
    
    
    interface Component{
    
        void operation();
    }
    
    class ConcreteComponent implements Component{
    
        @Override
        public void operation() {
            System.out.println("拍照");
        }
    }
    
    //装饰者类
    abstract  class Decorator implements  Component{
    
        Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
        
    
    }
    
    //装饰者1
    class ConcreteDecorator1 extends Decorator{
    
        //构造方法
        public ConcreteDecorator1(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            System.out.println("添加美颜");
            component.operation();
        }
    
    
    }
    
    //装饰者2
    class ConcreteDecorator2 extends Decorator{
    
        public ConcreteDecorator2(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            System.out.println("实现滤镜");
            component.operation();
        }
    }
    

    源码:

    javax.servlet.http.HttpServletRequestWrapper
    
  • 相关阅读:
    技术人生:墨菲定律
    Ioc:Autofac Registration Concepts
    Ioc:autofac lifetime scope.
    Ioc:The basic pattern for integrating Autofac into your application
    Logstash filter 插件之 date
    配置 Elasticsearch 集群
    Linux 命名管道
    Linux 管道
    Golang 入门 : channel(通道)
    Golang 入门 : 竞争条件
  • 原文地址:https://www.cnblogs.com/zhoujun007/p/13409981.html
Copyright © 2011-2022 走看看