大话设计模式六:装饰模式(穿什么有那么重要吗)

来源:互联网 发布:淘宝数据魔方多少钱 编辑:程序博客网 时间:2024/04/29 10:39

装饰模式
  动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
  装饰模式是为已有功能动态地添加更多功能的一种方式。
  装饰模式把每个要装饰的功能放在单独的类中,并让这个类包含它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象了。

 

装饰模式的优点是:
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 stubPerson 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 classclass Person {public Person() {}private String name;public Person(String name) {this.name = name;}public void Show() {System.out.println("装扮的"+this.name);}}//Decoratorclass Finery extends Person {protected Person component;public void Decorate(Person component) {this.component = component;}@Overridepublic void Show() {// TODO Auto-generated method stubif (component != null) {component.Show();}}}//ConcreteDecoratorclass TShirts extends Finery {@Overridepublic void Show(){System.out.println("T-shirt");super.Show();}}class BigTrouser extends Finery {@Overridepublic void Show() {System.out.println("big trouser");super.Show();}}class Sneakers extends Finery {@Overridepublic void Show() {System.out.println("sneaker");super.Show();}}class Suit extends Finery {@Overridepublic void Show() {System.out.println("suit");super.Show();}}class Tie extends Finery {@Overridepublic void Show() {System.out.println("Tie");super.Show();}}class LeatherShoes extends Finery {@Overridepublic void Show() {System.out.println("leatherShoes");super.Show();}}


原创粉丝点击