前言
一、面试
public abstract class Component {
public abstract void operation();}
public class ConcreteComponent extends Component {
@Override
public void operation() {
//基本功能的实现
}}
public class Decorator extends Component {
private Component component;//维持一个对抽象构件对象的引用
//注入一个抽象构件类型的对象
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();//调用原有的业务方法
}}
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation(){
super.operation();//调用原有业务方法
addedBehavior(); //调用新增业务方法
}
//新增业务方法
public void addedBehavior(){
//新增业务方法的具体内容
}}
public abstract class Component {
public abstract void display();}
public class Window extends Component{
@Override
public void display() {
System.out.println("显示窗体!");
}}
public class TextBox extends Component {
@Override
public void display() {
System.out.println("显示文本框!");
}}
public class ListBox extends Component {
@Override
public void display() {
System.out.println("显示列表框!");
}}
public class ComponentDecorator extends Component {
private Component component;//维持对抽象构件类型对象的引用
//注入抽象构件类型的对象
public ComponentDecorator(Component component) {
this.component = component;
}
@Override
public void display() {
component.display();
}}
public class ScrollBarDecorator extends ComponentDecorator {
public ScrollBarDecorator(Component component) {
super(component);
}
public void display(){
this.setScrollBar();
super.display();
}
public void setScrollBar(){
System.out.println("为构件增加滚动条!");
}}
public class BlackBorderDecorator extends ComponentDecorator {
public BlackBorderDecorator(Component component) {
super(component);
}
public void display(){
this.setScrollBar();
super.display();
}
public void setScrollBar(){
System.out.println("为构件增加黑色边框!");
}}
public class Test {
public static void main(String[] args) {
Component component,componentSB; //使用抽象构件定义对象
component = new Window(); //创建具体构件对象
componentSB = new ScrollBarDecorator(component);//创建装饰后的构件对象
componentSB.display();
}}
二、总结
原文始发于微信公众号(小奇JAVA面试):面试官:设计模式中的装饰模式是什么?
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/37715.html