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

    装饰类:

    package the_mass.decorator;
    
    import java.io.*;
    
    public class LogOutputStream extends OutputStream {
    
        private OutputStream os;
    
        public LogOutputStream(OutputStream outputStream) {
    
            this.os = outputStream;
        }
    
        @Override
        public void write(int b) throws IOException {
            this.os.write(b);
        }
    
        @Override
        public void write(byte[] b) throws IOException {
            System.out.println("开始了");
            super.write(b);
            System.out.println("结束了");
        }
    }

    充当进度条:

    package the_mass.decorator;
    
    import java.io.IOException;
    import java.io.OutputStream;
    
    public class ProgressOutStream extends OutputStream {
    
        private OutputStream os;
        public ProgressOutStream(OutputStream outputStream) {
            this.os=outputStream;
        }
    
        @Override
        public void write(int b) throws IOException {
            this.os.write(b);
        }
    
        @Override
        public void write(byte[] b) throws IOException {
            System.out.println(">>>>>>>>>>>>>");
            super.write(b);
        }
    }

    测试:

    package the_mass.decorator;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) throws IOException {
            FileOutputStream outputStream =new FileOutputStream("e:/aaa");
    
            LogOutputStream los = new LogOutputStream(outputStream);
            ProgressOutStream pos = new ProgressOutStream(outputStream);
            los.write("welcome".getBytes()); //使用指定的字符集将字符串编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
            pos.write("Hello wrold".getBytes());
    }
    }
  • 相关阅读:
    写在寒假
    Docker安装Redis(两种方式)
    JVM类加载机制
    RabbitMQ学习
    MySQL索引详解
    Java内存区域
    Window10下的Docker Desktop安装(保姆级教程)
    JVM垃圾回收
    力扣Hot100(目前进度89/100)
    C# 发送邮件实例
  • 原文地址:https://www.cnblogs.com/nongzihong/p/10193349.html
Copyright © 2011-2022 走看看