Java设计模式-----装饰模式

装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。

案例:窗体装饰

1.组件类

package Decorator; // 装饰者模式

/**
 * Created by Jiqing on 2016/10/13.
 */
abstract interface Component {
    public abstract void display();
}

2.组件装饰者

package Decorator;

/**
 * Created by Jiqing on 2016/10/13.
 */
public class ComponentDecorator implement Component{
    private Component component; // 维持对抽象构件类型对象的引用
    public ComponentDecorator(Component component){
        this.component = component;
    }

    public void display() {
        component.display();
    }

}

3.实现类ListBox

package Decorator;

/**
 * Created by Jiqing on 2016/10/13.
 */
public class ListBox implement Component{
    public void display() {
        System.out.println("显示列表框!");
    }
}

4.实现类TextBox

package Decorator;

/**
 * Created by Jiqing on 2016/10/13.
 */
public class TextBox extends Component{
    public void display() {
        System.out.println("显示文本框!");
    }
}

5.实现类Window

package Decorator;

/**
 * Created by Jiqing on 2016/10/13.
 */
public class Window implement Component{
    public void display() {
        System.out.println("显示窗体!");
    }
}

6.黑框装饰者

package Decorator;

/**
 * Created by Jiqing on 2016/10/14.
 */
public class BlackBoarderDecorator extends ComponentDecorator{
    public BlackBoarderDecorator(Component component) {
        super(component);
    }

    public void display() {
        this.setBlackBoarder();
        super.display();
    }

    public void setBlackBoarder() {
        System.out.println("为构件增加黑色边框!");

    }
}

7.滚动条装饰者

package Decorator;

/**
 * Created by Jiqing on 2016/10/14.
 */
public class ScrollBarDecorator extends ComponentDecorator{
    public ScrollBarDecorator (Component component) {
        super(component); // 调用父类构造函数
    }

    public void display() {
        this.setScrollBar();
        super.display();
    }

    public void setScrollBar() {
        System.out.println("为构件增加滚动条!");
    }
}

8.客户端调用

package Decorator; // 装饰者模式

/**
 * Created by Jiqing on 2016/10/14.
 */
public class Client {
    public static void main(String args[]) {
        Component component,componentSB,componentBB;
        component = new Window();
        componentSB = new ScrollBarDecorator(component);
        componentSB.display();
        System.out.println("--------------------");
        componentBB = new BlackBoarderDecorator(componentSB);
        componentBB.display();
    }
}

执行结果

为构件增加滚动条!
显示窗体!
--------------------
为构件增加黑色边框!
为构件增加滚动条!
显示窗体!

原文地址:https://www.cnblogs.com/zouzz/p/6596546.html