标签:装饰模式
装饰模式:类似代理
定义:动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。
设计初衷:通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。
定义超类:
public interface Source {
void say();
void sing();
}
具体实现(被装饰者):
public class SourceImpl implements Source {
public void say() {
System.out.println("hello");
}
public void sing() {
System.out.println("sing a song");
}
}
抽象装饰:装饰者与被装饰者拥有共同的超类,继承的目的是继承类型,而不是行为
public abstract class Decorator implements Source{
private Source source;
public Decorator(Source source) {
this.source = source;
}
public void say() {
this.source.say();
}
public void sing() {
this.source.sing();
}
}
装饰者1
public class D1 extends Decorator {
public D1(Source source) {
super(source);
}
@Override
public void say() {
super.say();
System.out.println("chen");
}
@Override
public void sing() {
super.sing();
System.out.println("吻别");
}
}
装饰者2
public class D2 extends Decorator {
public D2(Source source) {
super(source);
}
@Override
public void say() {
log("start say:");
super.say();
}
@Override
public void sing() {
log("start sing:");
super.sing();
}
public void log(String log){
System.out.println(log);
}
}
测试:
public class Client {
public static void main(String[] args) {
Source source = new SourceImpl();
Decorator decorator = new D2(new D1(source));
decorator.say();
decorator.sing();
}
}
结果:
start say:
hello
chen
start sing:
sing a song
吻别本文出自 “11898338” 博客,谢绝转载!
标签:装饰模式
原文地址:http://11908338.blog.51cto.com/11898338/1910012