装饰器模式:在不改变原有对象结构的基础上,向现有对象添加扩展新功能。
应用场景:动态扩展或撤销一个类的功能。
public class DecoratorPattern {
public static void main(String[] args) {
// MobilePhone xiaoMiMobilePhone = new XiaoMiMobilePhone();
// xiaoMiMobilePhone.operation();
MobilePhone xiaoMiMobilePhonePro = new MobilePhoneFilm(new MobilePhoneShell(new XiaoMiMobilePhone()));
xiaoMiMobilePhonePro.operation();
}
}
/**
* 手机
*/
interface MobilePhone {
void operation();
}
/**
* 小蜜手机
*/
class XiaoMiMobilePhone implements MobilePhone {
@Override
public void operation() {
System.out.println("打电话");
}
}
/**
* 装饰器
*/
abstract class Decorator implements MobilePhone {
MobilePhone mobilePhone;
public Decorator(MobilePhone mobilePhone) {
this.mobilePhone = mobilePhone;
}
}
/**
* 手机壳
*/
class MobilePhoneShell extends Decorator {
public MobilePhoneShell(MobilePhone mobilePhone) {
super(mobilePhone);
}
@Override
public void operation() {
System.out.println("加一个手机壳");
mobilePhone.operation();
}
}
/**
* 手机贴膜
*/
class MobilePhoneFilm extends Decorator {
public MobilePhoneFilm(MobilePhone mobilePhone) {
super(mobilePhone);
}
@Override
public void operation() {
System.out.println("贴膜");
mobilePhone.operation();
}
}