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

    装饰模式可以在不创造更多子类的情况下讲对象的功能加以扩展

    角色

    • 抽象构建角色:一个接口或抽象类,规范准备接受附加责任的对象(即具体构建角色)
    • 具体构建角色: 具体的,可以被装饰
    • 装饰角色:持有一个抽检构建的引用,已原逻辑实现抽闲构建角色的方法。
    • 具体装饰角色:可以装饰构建角色,也可以被装饰

    UML类图

    装饰角色持有构建角色引用,而且装饰角色中的方法和构建角色中的想用,实现方法使用构建角色引用对应的方法,及调用构建角色原本的实现方法
    具体装饰角色在重写方法时,再增加功能。

    javaIO 就是使用装饰模式。

    代码示例

    • 抽象构建角色:
    public interface Component {
        void doSomething();
    }
    
    
    • 具体构建角色:
    public class ConcreteComponent implements Component{
        @Override
        public void doSomething() {
            System.out.println("具体构建角色的功能");
        }
    }
    
    • 装饰角色:
    public class Decorator implements Component{
        private Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
    
        @Override
        public void doSomething() {
            component.doSomething();
        }
    }
    
    • 具体装饰角色(两个):
    public class ConcreteDecorator1 extends Decorator{
        public ConcreteDecorator1(Component component) {
            super(component);
        }
    
        @Override
        public void doSomething() {
            super.doSomething();
            this.doAnotherThing();
        }
    
        private void doAnotherThing(){
            System.out.println("具体装饰角色1的功能");
        }
    }
    
    public class ConcreteDecorator2 extends Decorator {
        public ConcreteDecorator2(Component component) {
            super(component);
        }
    
        @Override
        public void doSomething() {
            super.doSomething();
            this.doAnotherThing();
        }
    
        private void doAnotherThing(){
            System.out.println("具体装饰角色2的功能");
        }
    }
    
    • 调用:
    public class Client {
        public static void main(String[] args) {
            Component component = new ConcreteComponent();
    
            Component component2 = new ConcreteDecorator1(component);
    
            Component component3 = new ConcreteDecorator2(component2);
    
            component3.doSomething();
        }
    }
    
  • 相关阅读:
    AtCoder Tenka1 Programmer Beginner Contest 解题报告
    BZOJ4401: 块的计数 思维题
    LOJ#2170. 「POI2011」木棍 Sticks
    LOJ#2632. 「BalticOI 2011 Day1」打开灯泡 Switch the Lamp On
    LuoguP3183 [HAOI2016]食物链 记忆化搜索
    BZOJ2818: Gcd 欧拉函数
    BZOJ3942: [Usaco2015 Feb]Censoring 栈+KMP
    适用于Java的嵌入式脚本语言
    oracle goldengate的两种用法
    手滑把库给删了,跑路前应该做的事。。。
  • 原文地址:https://www.cnblogs.com/Theshy/p/8527347.html
Copyright © 2011-2022 走看看