Java 装饰模式 io流

在Java IO流的API中,大量的使用了装饰模式。

现在笔者来阐述一下装饰模式。


装饰模式的角色:

--抽象构件角色(Component): 给出一个抽象接口,以规范准备接收附加责任的对象。

--具体构件角色(Concrete Component):

定义一个将要接收附加责任的类。

--装饰角色(Decorator): 持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口。

--具体装饰角色(Concrete Decorator):负责给构件对象"贴上"附加的责任。


======================================


装饰模式和继承之间的对比:

1)装饰模式用于扩展特定对象的功能,而继承则是写死在类模板里面的。

2)对于一个给定的对象,同时可能有不同的装饰对象,客户端可以通过它的需要选择合适的装饰对象发送消息。而继承则需要不停的定义新的子类,造成java类的数量急剧上升

3)装饰模式更加灵活,继承则相对比较死板。。


笔者现在用代码来实现一下


package org.hl.decorator;
//抽象构件角色
public interface Component {
     void doSomething();
}


package org.hl.decorator;
//具体的构件角色,相当于FileOutputStream(节点流)
public class ConcreteComponent implements Component {
    @Override
    public void doSomething() {
        System.out.println("功能A");
    }
}


package org.hl.decorator;
//装饰角色,相当于FilterOutputStream(过滤流)
public class ConcreteDecorator extends ConcreteComponent {
    private Component component;

    public ConcreteDecorator(Component component) {
        this.component = component;
    }

    @Override
    public void doSomething() {
        component.doSomething();
    }
}

package org.hl.decorator;
//具体装饰角色,相当于BufferedOutputStream
public class DecoratorA extends ConcreteDecorator {

    public DecoratorA(Component component) {
        super(component);
    }

    @Override
    public void doSomething() {
        super.doSomething();
        this.doAnotherThing();
    }

    private void doAnotherThing() {
        System.out.println("装饰器提供的额外的功能A");
    }
}


package org.hl.decorator;

public class DecoratorB extends ConcreteDecorator {
    public DecoratorB(Component component) {
        super(component);
    }

    @Override
    public void doSomething() {
        super.doSomething();
        this.doAnotherThing();
    }

    private void doAnotherThing() {
        System.out.println("装饰器提供的额外的功能B");
    }
}

我们再来写个main 方法测试一下

package org.hl.decorator;

public class Client {
    public static void main(String[] args) {
        ConcreteComponent component = new DecoratorA(new DecoratorB(new ConcreteComponent()));
        component.doSomething();
    }
}


这样的写法是不是和 Java 的IO流API写法类似呢

OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream("a.txt"));



附上一张图片:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值