大话设计模式-装饰模式学习总结
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.
相关文章推荐
- 大话设计模式-原型模式学习总结
- 学习总结-设计模式理解(1) 参考《大话设计模式》《Delphi模式编程》
- 大话设计模式-解释器模式学习总结
- 大话设计模式-备忘录模式学习总结
- 大话设计模式学习(四)——装饰模式
- 大话设计模式-访问者模式学习总结
- 设计模式学习总结(8) 装饰模式
- 设计模式学习总结——装饰模式
- 大话设计模式-建造者模式学习总结
- 大话设计模式学习 装饰模式
- 大话设计模式-外观模式学习总结
- 大话设计模式-中介者模式学习总结
- 大话设计模式-职责链模式学习总结
- 设计模式学习总结-装饰模式(Decorator Method)
- 大话设计模式-命令模式学习总结
- 大话设计模式-观察者模式学习总结
- 大话设计模式学习(一)----装饰模式
- 大话设计模式-单例模式学习总结
- 基础学习总结之装饰设计模式
- 《大话设计模式》--OOTV杯超级模式大赛--模式总结(29-A)