文章内容输出来源:拉勾教育JAVA就业训练营
总目录跳转链接:总目录
设计模式总目录:【设计模式】设计模式(目录)
如有侵权请联系本人
邮箱:xiaogueika@tom.com
装饰器模式
1、基本概念
装饰器模式就是给一个对象动态的增加一些新功能,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例。
没有使用装饰类前
public interface Sourceable {
//自定义抽象方法
void method();
}
public class Source implements Sourceable{
@Override
public void method() {
System.out.println("--装饰模式--原有的功能");
}
}
public class SourceableTest {
public static void main(String[] args) {
Sourceable sourceable1 = new Source();
sourceable1.method();
}
}
装饰类
public class Decorator implements Sourceable {
private Sourceable source;
public Decorator(Sourceable source) {
this.source = source;
}
@Override
public void method() {
source.method();//保证原有功能不变
System.out.println("装饰类装饰的功能(后加功能)");
}
}
实现类
public class SourceableTest {
public static void main(String[] args) {
Sourceable sourceable1 = new Source();
sourceable1.method();
System.out.println("-------------------------");
//使用装饰类实现功能
Sourceable sourceable2 = new Decorator(sourceable1);
sourceable2.method();
}
}
突然说要加功能(使用装饰类效果)
3、实际意义
- 可以实现一个类功能的扩展。
- 可以动态的增加功能,而且还能动态撤销(继承不行)。
- 缺点:产生过多相似的对象,不易排错。