zoukankan      html  css  js  c++  java
  • 【设计模式】-结构型-4-装饰模式

    主要角色

    抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
    具体构件(Concrete Component)角色:实现抽象构件,通过装饰角色为其添加一些职责。
    抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
    具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

    代码示例

    package decorator;
    public class DecoratorPattern
    {
        public static void main(String[] args)
        {
            Component p=new ConcreteComponent();
            p.operation();
            System.out.println("---------------------------------");
            Component d=new ConcreteDecorator(p);
            d.operation();
        }
    }
    //抽象构件角色
    interface  Component
    {
        public void operation();
    }
    //具体构件角色
    class ConcreteComponent implements Component
    {
        public ConcreteComponent()
        {
            System.out.println("创建具体构件角色");       
        }   
        public void operation()
        {
            System.out.println("调用具体构件角色的方法operation()");           
        }
    }
    //抽象装饰角色
    class Decorator implements Component
    {
        private Component component;   
        public Decorator(Component component)
        {
            this.component=component;
        }   
        public void operation()
        {
            component.operation();
        }
    }
    //具体装饰角色
    class ConcreteDecorator extends Decorator
    {
        public ConcreteDecorator(Component component)
        {
            super(component);
        }   
        public void operation()
        {
            super.operation();
            addedFunction();
        }
        public void addedFunction()
        {
            System.out.println("为具体构件角色增加额外的功能addedFunction()");           
        }
    }
    

    著名示例

    BufferedReader in=new BufferedReader(new FileReader("filename.txtn));
    String s=in.readLine();
    
  • 相关阅读:
    Linux日志文件/var/log详解
    QT 的信号与槽机制介绍
    利用线程通信,写2个线程,一个线程打印1~52,另一个线程打印A~Z,打印顺序应该使12A34B56C···5152Z
    mysql快速安装
    zabbix安装源
    mysql手动安装
    没有可用软件包 zabbixservermysql
    【转载】web 部署专题(一):Gunicorn运行与配置方法
    supervisor快速配置
    linux监控脚本状态失败后拉起
  • 原文地址:https://www.cnblogs.com/tuofan/p/12334952.html
Copyright © 2011-2022 走看看