美文网首页
08.装饰模式

08.装饰模式

作者: 0x70e8 | 来源:发表于2018-03-19 18:57 被阅读0次

    装饰模式

    1.是什么

    装饰模式是以对客户端透明的方式(基于同一个接口)扩展对象的功能,是继承关系的一种替代方案。

    2.有什么用

    可以动态以插件的方式扩展原有类的功能,且对客户端透明

    3.怎么用
    • 通用类图


      decorator.png
    • 示例代码

    • component接口

    public interface IComponent {
    
        public void dosomeThing();
    }
    
    • component实现类
    public class BaseComponent implements IComponent {
    
        @Override
        public void dosomeThing() {
            System.out.println("this is basecomponent method");
        }
    
    }
    
    • 抽象装饰类
    public abstract class AbstractDecorator implements IComponent {
        private IComponent component;
    
        public AbstractDecorator(IComponent component) {
            this.setComponent(component);
        }
    
        /**
         * @return the component
         */
        public IComponent getComponent() {
            return component;
        }
    
        /**
         * @param component the component to set
         */
        public void setComponent(IComponent component) {
            this.component = component;
        }
    
    }
    
    • 装饰器实现类
    public class ConcreteDecorator1 extends AbstractDecorator {
    
        public ConcreteDecorator1(IComponent component) {
            super(component);
        }
    
        @Override
        public void dosomeThing() {
            System.out.println("This is decorator ConcreteDecorator1 method");
        }
    
    }
    public class ConcreteDecorator2 extends AbstractDecorator {
    
        public ConcreteDecorator2(IComponent component) {
            super(component);
        }
    
        @Override
        public void dosomeThing() {
            System.out.println("This is decorator ConcreteDecorator2 method");
        }
    
    }
    
    
    • Client类
    public class Client {
    
        public static void main(String[] args) {
            IComponent component = new BaseComponent();
            IComponent decorator1 = new ConcreteDecorator1(component);
            component.dosomeThing();
            decorator1.dosomeThing();
            IComponent decorator2 = new ConcreteDecorator2(component);
            decorator2.dosomeThing();
            IComponent decorator3 = new ConcreteDecorator2(decorator1);
            decorator3.dosomeThing();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:08.装饰模式

          本文链接:https://www.haomeiwen.com/subject/tanpqftx.html