作用:动态的将(责任)附加到(对象)上。易扩展。比继承好用
它的对象都可以单独使用,或者被装饰者 包装起来使用。
这里对象组件和装饰者 都共同继承某一类。是为了匹配同一对象,并且装饰者来替换对象组件。实现新加行为。
如果是继承,需要修改原程序。
继承的例子。
比如:我们要喝水,但是有的人会放很多的调味品。
public class Water {
public void drink() {
System.out.println("天哥喝水");
}
public static void main(String[] args) {
Sugar sugar = new Sugar();
sugar.drink();
sugar.addMilk();
sugar.addSugar();
}
}如果需要加牛奶的话。
public class Milk extends Water {
public void addMilk() {
System.out.println("+牛奶");
}
}如果需要加糖
public class Sugar extends Milk {
public void addSugar() {
System.out.println("+糖");
}
}你会发现每次加一个都需要继续去继承。很死板,很僵硬。而且调料类会越来越多。
而装饰模式:
1.抽象组件 (水)
2.具体组件 (矿泉水,纯净水,自来水)
3.装饰者 (牛奶,糖)
具体组件 和 装饰者 都继承抽象组件。装饰者 要有抽象组件 的引用。
可以根据 装饰者组合,产生新的类。
不断地组合就可以产生需要的类。
//抽象组件
public interface Component {
void doSomething();
}//具体组件
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("天哥喝水");
}
}//装饰角色
public class Decorator implements Component { //对具体组件的引用
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void doSomething() {
component.doSomething();
}
}//具体装饰者
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void doSomething() {
super.doSomething();
this.doOtherThing();
}
public void doOtherThing() {
System.out.println("+冰糖");
}
}执行:
public class Main {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator1 = new ConcreteDecorator(component);
Decorator decorator2 = new ConcreteDecorator2(decorator1);
decorator2.doSomething();
}
}为什么都继承Component这个类,是要在构造方法中传入真的对象。
也就相当于
Component component = new ConcreteDecorator2(new ConcreteDecorator(new ConcreteComponent()));
component.doSomething();
这就是java中I/O流的设计模式。
本文通过喝水加调料的例子,对比了继承和装饰模式的不同。装饰模式允许动态地为对象添加职责,比继承更灵活,更适合扩展。文章详细介绍了装饰模式的组成部分:抽象组件、具体组件和装饰者,并提供了具体的Java代码示例。
1260

被折叠的 条评论
为什么被折叠?



