透明装饰模式
在透明装饰模式中,要求客户端完全针对抽象编程;
Component c, c1; //使用抽象构件类型定义对象
c = new ConcreteComponent();
c1 = new ConcreteDecorator (c);
而不应该使用如下代码:
ConcreteComponent c; //使用具体构件类型定义对象
c = new ConcreteComponent();
或
ConcreteDecorator c1; //使用具体装饰类型定义对象
c1 = new ConcreteDecorator(c);
半透明装饰模式
具体构件类型无须关心,是透明的;但是具体装饰类型必须指定,这是不透明的。
Document doc; //使用抽象构件类型定义
doc = new PurchaseRequest();
Approver newDoc; //使用具体装饰类型定义
newDoc = new Approver(doc);
两者区别
- 半透明装饰模式可以给系统带来更多的灵活性,设计相对简单,使用起来也非常方便。
- 但是其最大的缺点在于不能实现对同一个对象的多次装饰。
- 而且客户端需要有区别地对待装饰之前的对象和装饰之后的对象。
透明装饰模式代码示例


//抽象界面构件类:抽象构件类
abstract class Component {
public abstract void display();
}
//窗体类:具体构件类
class Window extends Component {
public void display() { System.out.println("显示窗体!"); }
}
//文本框类:具体构件类
class TextBox extends Component {
public void display()
{
System.out.println("显示文本框!");
}
}
//列表框类:具体构件类
class ListBox extends Component {
public void display()
{
System.out.println("显示列表框!");
}
}
//构件装饰类:抽象装饰类
class ComponentDecorator extends Component {
//维持对抽象构件类型对象的引用
private Component component;
//注入抽象构件类型的对象
public ComponentDecorator(Component component) { this.component = component; }
public void display() { component.display(); }
}
//滚动条装饰类:具体装饰类
class ScrollBarDecorator extends ComponentDecorator {
public ScrollBarDecorator(Component component) {
super(component);
}
public void display() {
this.setScrollBar();
super.display();
}
public void setScrollBar() {
System.out.println("为构件增加滚动条!");
}
}
//滚动条装饰类:具体装饰类
class BlackBorderDecorator extends ComponentDecorator {
public BlackBorderDecorator(Component component) {
super(component);
}
public void display() {
this.setScrollBar();
super.display();
}
public void setScrollBar() {
System.out.println("为构件增加黑色边框!");
}
}
class Client {
public static void main(String args[]) {
Component component, componentSB, componentBB; //全部使用抽象构件定义
component = new Window();
componentSB = new ScrollBarDecorator(component);
componentBB = new BlackBorderDecorator(componentSB); //将装饰了一次之后的对象继续注入到另一个装饰类中,进行第二次装饰
componentBB.display();
}
}
网友评论