在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) {
ponent = 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 = newBufferedOutputStream(newFileOutputStream("a.txt"));
附上一张图片:
如果觉得《java装饰模式模拟流_Java 装饰模式 io流》对你有帮助,请点赞、收藏,并留下你的观点哦!