裝飾模式:動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更加靈活。裝飾模式結構圖如下
裝飾模式適用場合:當需要給系統添加新的功能時,而這些添加的功能僅僅是爲了滿足一些只在某種特定情況下才會執行的特殊行爲的需要,它把每個裝飾的功能放在單獨的類中,並讓這個類包裝它所要裝飾的對象,因此,當需要執行特殊行爲時,客戶端就可以在運行時候根據需要有選擇地、按順序地使用裝飾功能包裝對象。
以小明搭配衣服爲例。
定義一個IPerson接口
public interface IPerson {
public void show();
}
定義一個具體對象Person
public class Person implements IPerson {
private String name;
public Person(){
}
public Person(String name){
this.name=name;
}
@Override
public void show() {
System.out.println("打扮的"+name);
}
}
定義一個裝飾類Finery繼承IPerson
public class Finery implements IPerson{
protected IPerson person;
//打扮
public void decorate(IPerson person){
this.person=person;
}
@Override
public void show() {
if(person!=null){
person.show();
}
}
}
定義若干個具體的裝飾對象,繼承裝飾類Finery
public class Tshirt extends Finery {
public void show(){
System.out.print("T恤衫,");
super.show();
}
}
public class Trouser extends Finery{
public void show(){
System.out.print("褲子,");
super.show();
}
}
public class LeaterShoes extends Finery{
public void show(){
System.out.print("皮鞋,");
super.show();
}
}
public class NetShoes extends Finery {
public void show(){
System.out.print("網鞋,");
super.show();
}
}
public class Suit extends Finery{
public void show(){
System.out.print("西裝,");
super.show();
}
}
客戶端代碼
public static void main(String[] args) {
//裝飾模式
Person person=new Person("小明");
//第一種裝扮
System.out.println("第一種裝扮 :");
NetShoes nShoes=new NetShoes();//T恤衫
Trouser trouser=new Trouser();//褲子
Tshirt tshirt=new Tshirt();//網鞋
nShoes.decorate(person);
trouser.decorate(nShoes);
tshirt.decorate(trouser);
tshirt.show();
//第二種裝扮
System.out.println("第二種裝扮 :");
LeaterShoes lShoes=new LeaterShoes();//西裝
Trouser nTrouser=new Trouser();//褲子
Suit suit =new Suit();//皮鞋
lShoes.decorate(person);
nTrouser.decorate(lShoes);
suit.decorate(nTrouser);
suit.show();
}
結果顯示:
第一種裝扮 :
T恤衫,褲子,網鞋,打扮的小明
第二種裝扮 :
西裝,褲子,皮鞋,打扮的小明