装饰模式通常是为了在已有功能动态的添加更多功能的一种方式,这些新加的代码通常装饰了原有类的核心职责或者主要行为。而这些新加入的东西仅仅为了满足一些只在某种特定情况下才会执行的特殊行为的需要,装饰器模式将每个要装饰的功能放在单独的类中,并让这个类包装它要装饰的对象。因此,在需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序的使用装饰器功能包装对象。有效地把类的核心职责和装饰功能区分开了。
package DesignPattern.DecoratorPattern;
public class Person {
public Person(){
}
private String name;
public Person(String name){
this.name=name;
}
public void show(){}
}
package DesignPattern.DecoratorPattern;
public class Finery extends Person {
protected Person component;
public void decorate(Person component){
this.component=component;
}
@Override
public void show() {
if(component!=null)
component.show();
}
}
具体装饰类
package DesignPattern.DecoratorPattern;
public class BigTrouser extends Finery {
@Override
public void show() {
System.out.print("垮裤 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class LeatherShoes extends Finery {
@Override
public void show() {
System.out.print("皮鞋 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Sneaker extends Finery {
@Override
public void show() {
System.out.print("运动鞋 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Suit extends Finery {
@Override
public void show() {
System.out.print("领带 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Tshirts extends Finery {
@Override
public void show() {
System.out.print("大T恤 ");
this.component.show();
}
}
package DesignPattern.DecoratorPattern;
public class Client {
public static void main(String[] args){
Person xc=new Person("小明");
System.out.println("第一种装扮:");
Sneaker pqx=new Sneaker();
BigTrouser bt=new BigTrouser();
Tshirts ts=new Tshirts();
pqx.decorate(xc);
bt.decorate(pqx);
ts.decorate(bt);
ts.show();
System.out.println("\n第二种装扮");
LeatherShoes px=new LeatherShoes();
Tie ld=new Tie();
Suit su=new Suit();
px.decorate(xc);
ld.decorate(px);
su.decorate(ld);
su.show();
}
}
本文深入探讨了装饰模式在软件设计中的应用,通过实例演示了如何在不改变原有代码的情况下,动态地为对象添加新的职责和行为。装饰模式通过将装饰功能放入独立的类中,实现了核心职责与装饰功能的有效分离。
1392

被折叠的 条评论
为什么被折叠?



