装饰者模式:通过组合对已有代码进行装饰。根据不同功能拆分装饰器,装饰器可以装饰一类对象,同一个对象可以被不同的装饰器装饰,使用时自由组合装饰器与实例得到不同的结果
public abstract class People {
public abstract void cry();
}
public class Man extends People {
@Override
public void cry() {
System.out.print(" 男孩:呜呜呜呜~");
}
}
public class Woman extends People {
@Override
public void cry() {
System.out.print(" 女孩:啊啊啊啊~");
}
}
public class SobbingCryDecorator {
private People people;
public void cry() {
System.out.print("小声啜泣,发出~~~");
people.cry();
System.out.println("的声音");
}
public void setPeople(People people) {
this.people = people;
}
}
public class NoiseCryDecorator {
private People people;
public void cry() {
System.out.print("大声喧哗,发出~~~");
people.cry();
System.out.println("的声音");
}
public void setPeople(People people) {
this.people = people;
}
}
public class TestDemo {
public static void main(String[] args) {
People man = new Man();
People woman = new Woman();
NoiseCryDecorator noiseCryDecorator = new NoiseCryDecorator();
SobbingCryDecorator sobbingCryDecorator = new SobbingCryDecorator();
//男孩子吵闹
noiseCryDecorator.setPeople(man);
noiseCryDecorator.cry();
//女孩子委屈
sobbingCryDecorator.setPeople(woman);
sobbingCryDecorator.cry();
//男孩子委屈
sobbingCryDecorator.setPeople(man);
sobbingCryDecorator.cry();
}
}