您的位置:首页 > 其它

设计模式之【装饰者--Decorator】

2015-07-24 17:01 507 查看
1、接口

package Decorator;

public interface Sourceable {
public void method();

}


2、接口实现类--被装饰者

package Decorator;

public class Source implements Sourceable{

@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("接口原始方法的实现");
}

}


3、装饰类

package Decorator;

//装饰类,在原有类的基础上通过接口添加新方法
public class Decorator implements Sourceable{
private Sourceable source;

public Decorator(Sourceable source){
super();    //调用父类构造方法
this.source = source;
}

@Override
public void method() {
// TODO Auto-generated method stub
System.out.println("装饰前");
source.method();
System.out.println("装饰后");
}

}


4、实现扩展

package Decorator;

public class DecoratorTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
Sourceable    source = new Source();
Sourceable    obj = new Decorator(source);
obj.method();
}

}


5、结果

装饰前
接口原始方法的实现
装饰后


装饰器模式的应用场景:

1、需要扩展一个类的功能。

2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)

缺点:产生过多相似的对象,不易排错!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: