當想要對已有的對象進行功能增強時,可以定義類,將已有對象傳入,基於已有的功能,並提供加強功能。那麼自定義的該類稱爲裝飾類。裝飾類和原來的類常常屬於同一個接口。
裝飾類通常會通過構造方法接收被裝飾的對象,並給予被裝飾的對象的功能提供更強的功能。
//原有的類
class Person {
public void eat() {
System.out.println("吃飯");
}
}
//裝飾類,對本來的Person類進行裝飾
class SuperPerson {
private Person p;
SuperPerson(Person p) { //構造函數,爲了增強別的對象而存在
this.p = p;
}
public void superEat() {
System.out.println("開胃酒");
p.eat(); //System.out.println("吃飯");
System.out.println("甜點");
System.out.println("來一根");
}
}
class PersonDemo {
public static void main(String[] args) {
Person p = new Person();
//p.eat();
SuperPerson sp = new SuperPerson(p);
sp.superEat();
}
}
裝飾和繼承的區別
裝飾和集成都能實現一樣的特點:進行功能的擴展增強。他們的區別是什麼呢?
答:
裝飾比繼承靈活。
裝飾類和被裝飾類都必須所屬同一個接口或父類。