您的位置:首页 > 其它

大话设计模式-装饰模式学习总结

2018-01-14 14:17 441 查看

一、概念

装饰模式,动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

二、类图



三、实例之穿衣

//抽象装饰者
public abstract class Finery extends Person{
private Person component;

public void Decorate(Person component){
this.component=component;
}

@Override
public void Show() {
if(component!=null){
component.Show();
}
}

}
//具体装饰者
public class BigTrouser extends Finery{

@Override
public void Show() {
System.out.println("跨裤");
super.Show();
}

}
//具体装饰者
public class TShirts extends Finery{

@Override
public void Show() {
System.out.println("大T恤");
super.Show();
}

}


//人--->被装饰者
public class Person {
private String name;

public Person(){

}

public Person(String name){
this.name=name;
}

public void Show(){
System.out.println("装扮的:"+name);
}

}


//客户端
public class Show {
public static void main(String[] args) {
Person person=new Person("hwj");
TShirts tShirts=new TShirts();
BigTrouser bigTrouser=new BigTrouser();

tShirts.Decorate(person);
bigTrouser.Decorate(tShirts);
//      tShirts.Show();
bigTrouser.Show();

}

}


四、总结

1、设计模式并不是一成不变的,在实际情况中,可进行适当的变形,如上述穿衣案例中,省去了Comonent,让Decorator(Finery)直接继承ConcreteComonent(Person)。

2、使用时机。在要动态地给一个对象增加功能,这些功能可再动态地被撤销时可使用装饰模式。

3、装饰模式与继承关系的目的都是要拓展对象的功能,但是装饰模式可以提供比继承关系更多的灵活性,通过使用不同的具体装饰类以及这些装饰类的排列组合,可以创造出很多相同行为的组合。

One may overcome a thousand men in battle,but he who conquers himself is the greatest victor.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息