装饰模式把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象。
案例:穿搭。衣柜有帽子、眼镜、冲锋衣和毛衣,现在请你选择一件或多件物品穿搭出门。使用装饰模式打印出不同的方案。
package Decorator;public class Cap extends Finary{@Overridepublic void show() {System.out.print("帽子 ");super.show();}
}
package Decorator;public class Finary extends Person{private Person component;public void decorate(Person component) {this.component = component;}@Overridepublic void show() {if(component!=null) {component.show();};}
}
package Decorator;public class Glasses extends Finary{@Overridepublic void show() {System.out.print("眼镜 ");super.show();}
}
package Decorator;public class OutdoorJacket extends Finary{@Overridepublic void show() {System.out.print("冲锋衣 ");super.show();}
}
package Decorator;public class Person {private String name;public Person() {}public Person(String name) {this.name = name;}public void show() {System.out.println("(" + name + ")");;}
}
package Decorator;public class Sweater extends Finary{@Overridepublic void show() {System.out.print("毛衣 ");super.show();}
}
package Decorator;public class Client {public static void main(String[] args) {Person z = new Person("张三");Cap cap = new Cap();Glasses glasses = new Glasses();OutdoorJacket oj = new OutdoorJacket();cap.decorate(z);glasses.decorate(cap);oj.decorate(glasses);oj.show();Person l = new Person("李四");Sweater sweater = new Sweater();sweater.decorate(l);sweater.show();}
}
上述模式是透明模式,还有一种模式是半透明模式。二者的主要区别在于半透明模式子类重写父类的方法时并未调用父类的方法,修饰对象无法多次修饰。
冲锋衣 (张三)
毛衣 (李四)