JDK中的设计模式--桥接模式

java.util.logging是JDK自带的日志包,可以将日志输出到文件、内存或者控制台,作用与我们常用的log4j类似。
包中的Handler类和Formatter类在设计上利用了桥接模式,首先看类关系图:
在这里插入图片描述
Handle和Formatter类是两个抽象类,它们可以分别独立的变化(有不同的子类);而Handle类中包含对Formatter类的引用。

 //handle类中的set方法
  public synchronized void setFormatter(Formatter newFormatter) throws SecurityException {
        checkPermission();
        // Check for a null pointer:
        newFormatter.getClass();
        formatter = newFormatter;
    }

Handle通过setFormatter方法可以方便的替换不同的Formatter类。

Handle与Formatter介绍
1、Handle.
来自JDK本身的介绍:

/**
 * A <tt>Handler</tt> object takes log messages from a <tt>Logger</tt> and
 * exports them.  It might for example, write them to a console
 * or write them to a file, or send them to a network logging service,
 * or forward them to an OS log, or whatever.
 * <p>
 * A <tt>Handler</tt> can be disabled by doing a <tt>setLevel(Level.OFF)</tt>
 * and can  be re-enabled by doing a <tt>setLevel</tt> with an appropriate level.
 * <p>
 * <tt>Handler</tt> classes typically use <tt>LogManager</tt> properties to set
 * default values for the <tt>Handler</tt>'s <tt>Filter</tt>, <tt>Formatter</tt>,
 * and <tt>Level</tt>.  See the specific documentation for each concrete
 * <tt>Handler</tt> class.
 *
 *
 * @since 1.4
 */

handle对象可以从一个logger中取出信息并输出到控制台、文件或者调用其它api发送到网络中;
handle可以通过setLevel方法关闭或打开;
handle通常是利用LogManager去设置自身的Handler、Filter、Formatter等属性值。
*备注虽然父类Handle中提供了setFormatter方法,但子类streamhandle中也重新提供了配置各个成员变量值的方法:

 private void configure() {
        LogManager manager = LogManager.getLogManager();
        String cname = getClass().getName();
        setLevel(manager.getLevelProperty(cname +".level", Level.INFO));
        setFilter(manager.getFilterProperty(cname +".filter", null));
        setFormatter(manager.getFormatterProperty(cname +".formatter", new SimpleFormatter()));
        try {
            setEncoding(manager.getStringProperty(cname +".encoding", null));
        } catch (Exception ex) {
            try {
                setEncoding(null);
            } catch (Exception ex2) {
                // doing a setEncoding with null should always work.
                // assert false;
            }
        }
    }

2、Formatter
JDK的介绍:

/**
 * A Formatter provides support for formatting LogRecords.
 * <p>
 * Typically each logging Handler will have a Formatter associated
 * with it.  The Formatter takes a LogRecord and converts it to
 * a string.
 * <p>
 * Some formatters (such as the XMLFormatter) need to wrap head
 * and tail strings around a set of formatted records. The getHeader
 * and getTail methods can be used to obtain these strings.
 *
 * @since 1.4
 */

Formatter支持格式化日志数据;通常每个Handler中都会有一个Formatter引用,Formatter可以将LogRecord对象转换为一个string字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值