装饰者模式

1 . 装饰者模式:父类中原有此功能,子类 想要在父类的这个功能的基础上增加一些其他的功能
2 .父类

package com.qf.demo3;

public class Util {

    public  void  print99(){
        for (int i = 1; i <=9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i+"*"+j+"="+i*j+"\t");
            }
            System.out.print("\n");
        }
    }
}

3 . 子类

package com.qf.demo3;

public class SonUtil extends Util{

    private Util util;

    public SonUtil(Util util) {
        super();
        this.util = util;
    }

    @Override
    public  void print99() {
        // 前期准备
        System.out.println("以下是高端大气上档次的99乘法表");
//      super.print99();
        util.print99();     
        // 完成以后
        System.out.println("以上是低调奢华有内涵的99乘法表");

    }
}

4 .主方法main

package com.qf.demo3;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * 装饰者模式
 *      父类中原有此功能
 *      子类 想要在父类的这个功能的基础上增加一些其他的功能
 *      
 */
public class Test {

    public static void main(String[] args) {
//      Util util = new Util();
//      util.print99();
//      
        SonUtil sonUtil  = new SonUtil(new Util());
        sonUtil.print99();
        sonUtil.print99();
        sonUtil.print99();
        sonUtil.print99();
        sonUtil.print99();

        // 流用到装饰者模式
    //  BufferedReader reader = new BufferedReader(new FileReader(file))
    }
}

总结:父类和子类的代码是用来简单的介绍什么是装饰者模式,流也是用到了装饰者模式.
// BufferedReader reader = new BufferedReader(new FileReader(file))

解释:本来父类Reader有reader()方法,但是读取数据没有缓冲流快,则子类字符缓冲流装饰了父类的reader方法,速度变快.BufferedReader构造方法中要求写的是父类的对象,但是现在看BufferedReader的构造方法是FileReader对象,但是这FileReader父类也是Reader,可以向上转型为Reader对象.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值