安徽省住房和城乡建设厅网站查询,厦门网站建设商家,wap网站建设免费,计算机网络技术就业方向专科作用#xff1a;在不修改对象外观和功能的情况下添加或者删除对象功能#xff0c;即给一个对象动态附加职能
装饰器模式主要包含以下角色。
抽象构件#xff08;Component#xff09;角色#xff1a;定义一个抽象接口以规范准备接收附加责任的对象。具体构件#xff08…作用在不修改对象外观和功能的情况下添加或者删除对象功能即给一个对象动态附加职能
装饰器模式主要包含以下角色。
抽象构件Component角色定义一个抽象接口以规范准备接收附加责任的对象。具体构件ConcreteComponent角色实现抽象构件通过装饰角色为其添加一些职责。抽象装饰Decorator角色继承抽象构件并包含具体构件的实例可以通过其子类扩展具体构件的功能。具体装饰ConcreteDecorator角色实现抽象装饰的相关方法并给具体构件对象添加附加的责任。 package decorator;
public class DecoratorPattern {public static void main(String[] args) {Component p new ConcreteComponent();p.operation();System.out.println(---------------------------------);Component d new ConcreteDecorator(p);d.operation();}
}
//抽象构件角色
interface Component {public void operation();
}
//具体构件角色
class ConcreteComponent implements Component {public ConcreteComponent() {System.out.println(创建具体构件角色);}public void operation() {System.out.println(调用具体构件角色的方法operation());}
}
//抽象装饰角色
class Decorator implements Component {private Component component;public Decorator(Component component) {this.component component;}public void operation() {component.operation();}
}
//具体装饰角色
class ConcreteDecorator extends Decorator {public ConcreteDecorator(Component component) {super(component);}public void operation() {super.operation();addedFunction();}public void addedFunction() {System.out.println(为具体构件角色增加额外的功能addedFunction());}
}
运行结果
创建具体构件角色
调用具体构件角色的方法operation()
---------------------------------
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()