装饰模式
概述
动态地为原有类添加新的功能。
而不是以继承的方式来扩展,避免不断增加子类;
不是以增加新字段、新方法的方式扩展新功能,将核心功能与装饰功能区分。
举例
给人穿衣服
涉及的类:
Person类
interface Person{
public void show();
}
Male类
class Male implements Person{
@Override
public void show() {
System.out.println("male show");
}
}
Female类
class Female implements Person{
@Override
public void show() {
System.out.println("female show");
}
}
ClothDecorator类
abstract class ClothDecorator implements Person{
protected Person component;
public void setComponent(Person component){
this.component = component;
}
@Override
public void show() {
if (component != null){
component.show();
}
}
}
抽象装饰类持有一个所需装饰对象的引用,通过setComponent方法实现对象的包装;
并继承/实现它所要装饰的类/接口,重写需要装饰的功能,即调用所装饰对象的相应方法;
然后,具体装饰类就只需实现自己的装饰功能,再调用父类相应方法即可。
SkirtDecorator类
class SkirtDecorator extends ClothDecorator{
@Override
public void show() {
System.out.println("穿裙子");
super.show();
}
}
TieDecorator类
class TieDecorator extends ClothDecorator{
@Override
public void show() {
System.out.println("打领带");
super.show();
}
}
SuitDecorator类
class SuitDecorator extends ClothDecorator{
@Override
public void show() {
System.out.println("穿西装");
super.show();
}
}
客户端
Person male = new Male();
Person female = new Female();
SkirtDecorator skirtDecorator = new SkirtDecorator();
TieDecorator tieDecorator = new TieDecorator();
SuitDecorator suitDecorator = new SuitDecorator();
suitDecorator.setComponent(male);
tieDecorator.setComponent(suitDecorator);
skirtDecorator.setComponent(tieDecorator);
skirtDecorator.show();
skirtDecorator.setComponent(female);
skirtDecorator.show();