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();
        }
    }
    
  • 相关阅读:
    Cnic.SafeNativeMethods
    KnockOut文档--模板绑定
    luoguP1120 小木棍 [数据加强版]
    luoguP1951 收费站_NOI导刊2009提高(2)
    luoguP1821 [USACO07FEB]银牛派对Silver Cow Party
    luoguP2991 [USACO10OPEN]水滑梯Water Slides
    luoguP4198 楼房重建
    (数位dp)吉利数字 区间k大
    数字游戏
    Amount of Degrees
  • 原文地址:https://www.cnblogs.com/Theshy/p/8527347.html
Copyright © 2011-2022 走看看