装饰者模式
2018-12-13 本文已影响0人
CoderZzbJohn
Source:被装饰对象
Decorator:装饰者父类,继承Source。该对象中有一个source实例
DecoratorA: 具体的装饰者。继承Decorator,自己的方法+supper中的方法。
DecoratorB: 具体的装饰者。继承Decorator,自己的方法+supper中的方法。
public class Source {
public void sing(){
System.out.println("sing..");
}
}
public class Decorate extends Source {
private Source source;
public Decorate(Source source) {
this.source = source;
}
@Override
public void sing() {
source.sing();
}
}
public class DecorateA extends Decorate {
public DecorateA(Source source) {
super(source);
}
@Override
public void sing() {
dance();
super.sing();
}
public void dance() {
System.out.println("dance...");
}
}
public class DecorateB extends Decorate {
public DecorateB(Source source) {
super(source);
}
@Override
public void sing() {
cry();
super.sing();
}
public void cry() {
System.out.println("cry...");
}
}
public class Client {
public static void main(String[] args) {
Source source = new Source();
Source decorateA = new DecorateB(new DecorateA(source));
decorateA.sing();
}
}