设计模式 装饰模式
装饰(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。
public class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void show() {
component.show();
System.out.println("抽象装饰角色");
}
}
public interface Component {
public void show();
}
public class ConcreteComponent implements Component {
@Override
public void show() {
System.out.println("角色的方法");
}
}
public class ConcreteDecorator extends Decorator{
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void show() {
super.show();
System.out.println("增加额外的功能");
}
}
本文深入探讨了装饰模式,一种允许在不修改对象结构的前提下为其添加新功能的设计模式。通过具体实例,展示了如何使用装饰者模式来扩展对象的行为,而无需通过继承。文章详细解释了装饰模式的实现方式,包括抽象组件、具体组件、装饰者和具体装饰者的角色。

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



