装饰模式
动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式是为已有功能动态地添加更多功能的一种方式。
装饰模式把每个要装饰的功能放在单独的类中,并让这个类包含它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象了。
装饰模式的优点是:
1.把类中的装饰功能从类中搬移去除,这样可以简化原有的类。
2.有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
装饰器相当于一个累加的过程,c累加到d1,再把d1累加到d2,类似于d2(d1(c))
package Decorator;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person xc = new Person("jack");
System.out.println("First decoration");
Sneakers sneakers = new Sneakers();
BigTrouser bigTrouser = new BigTrouser();
TShirts tShirts = new TShirts();
sneakers.Decorate(xc);
bigTrouser.Decorate(sneakers);
tShirts.Decorate(bigTrouser);
tShirts.Show();
}
}
//ConcreteComponent class
class Person {
public Person() {}
private String name;
public Person(String name) {
this.name = name;
}
public void Show() {
System.out.println("装扮的"+this.name);
}
}
//Decorator
class Finery extends Person {
protected Person component;
public void Decorate(Person component) {
this.component = component;
}
@Override
public void Show() {
// TODO Auto-generated method stub
if (component != null) {
component.Show();
}
}
}
//ConcreteDecorator
class TShirts extends Finery {
@Override
public void Show(){
System.out.println("T-shirt");
super.Show();
}
}
class BigTrouser extends Finery {
@Override
public void Show() {
System.out.println("big trouser");
super.Show();
}
}
class Sneakers extends Finery {
@Override
public void Show() {
System.out.println("sneaker");
super.Show();
}
}
class Suit extends Finery {
@Override
public void Show() {
System.out.println("suit");
super.Show();
}
}
class Tie extends Finery {
@Override
public void Show() {
System.out.println("Tie");
super.Show();
}
}
class LeatherShoes extends Finery {
@Override
public void Show() {
System.out.println("leatherShoes");
super.Show();
}
}