设计模式(3)---- 装饰者模式

    定义:The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. (装饰者模式可以动态地给一个对象增加其他职责。就扩展对象功能来说,装饰者模式比生成子类更为灵活。)

    特点:

A. 装饰对象和真实对象有相同的接口,这样客户端对象就可以以和真是对象相同的方式和装饰对象交互。

B. 装饰对象包含一个真实对象的索引

C. 装饰对象接受所有来自客户端的请求,它把这些请求转发给真实对象

D. 装饰对象可以在转发这些请求以前或以后增加一些附加功能,这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能,在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

 

    装饰者类图:

   Component(被装饰对象基类)  

        定义对象的接口,可以给这些对象动态增加职责;

   ConcreteComponent(具体被装饰对象)

        定义具体的对象,Decorator可以给它增加额外的职责;

   Decorator(装饰者抽象类)

       维护一个指向Component实例的引用,并且定义了与Component一致的接口;

   ConcreteDecorator(具体装饰者)

      具体的装饰对象,给内部持有的具体被装饰对象增加具体的职责;

 

 

代码
代码:
1.被装饰对象基类
Public
interface Component {
publicvoid go();
}
2. 具体被装饰对象
Public
class ConcreteComponent implements Component {
Public
void go() {
System.out.println(
"行走");
}
}
3. 装饰者抽象类
Public
class Decorator implements Component {
private Component component;
protected Decorator(Component component) {
this.component = component;
}
publicvoid go() {
this.component.go();
}
}

4. 具体装饰者a
Public
class ConcreteDecoratorListen extends Decorator {
public ConcreteDecoratorListen(Component component) {
super(component);
// code is here
}
publicvoid go() {
listen(
"听音乐");//执行扩展功能
super.go();
}

privatevoid listen(Object obj){
System.out.println(obj);
}
}


5. 具体装饰者b
Public
class ConcreteDecoratorSing extends Decorator {
public ConcreteDecoratorSing(Component component) {
super(component);
// code is here
}
publicvoid go() {
super.go();
System.out.println(sing());;
// 执行扩展功能
}
private String sing() {
return"唱歌";
}
}
6.测试
publicclass Main {
publicstaticvoid main(String[] args) {
Component component
= new ConcreteComponent();
ConcreteDecoratorListen cdl
= new ConcreteDecoratorListen(component);
cdl.go();
System.out.println();
ConcreteDecoratorSing cds
= new ConcreteDecoratorSing(component);
cds.go();
}
}

优点:装饰模式和继承都是对功能的扩展,而装饰模式使用的是组合,可以不用继承而达到这一效果.使用过多的继承会增加系统的复杂性和耦合性

缺点:装饰模式要产生一些辅助性的对象,但这些对象看上去都比较像,不是很容易检查,好的命名应该是提高检查的一个办法

posted @ 2010-07-10 17:00  gistone  Views(248)  Comments(0)    收藏  举报