你有一座房子,你要装修你的房子
对已有对象增加新功能,而不改变该对象。
package structural.pratice; public class Decoretor2PMain { public static void main(String[] args) { House f = new FirstHouse(); DecoretationWorker worker = new DecoretationWorker(f); worker.wholeHouse(); } } //房子设计图 interface House{ void beWall(); void beWindows(); void beDoors(); void beRoof(); void beFloor(); void wholeHouse(); } //建造房子 class FirstHouse implements House{ @Override public void beWall() { System.out.println("建好了墙!"); } @Override public void beWindows() { System.out.println("建好了窗户!"); } @Override public void beDoors() { System.out.println("建好了门!"); } @Override public void beRoof() { System.out.println("建好了房顶!"); } @Override public void beFloor() { System.out.println("建好了地板!"); } @Override public void wholeHouse() { beWall(); beWindows(); beDoors(); beRoof(); beFloor(); } } //装修房子 abstract class DecoreteHouse extends FirstHouse{//extends FirstHouse到房子所在位置装修 protected House f; public DecoreteHouse(House f){ this.f = f; } } class DecoretationWorker extends DecoreteHouse{ public DecoretationWorker(House f) { super(f); } @Override public void wholeHouse() { super.wholeHouse(); System.out.println(); System.out.println("======房子已建好!======="); System.out.println(); installAppliances(); installKitchenToilet(); installFurniture(); installFurniture(); beautifyOrnament(); bedclothes(); buyOthers(); } public void installAppliances(){ System.out.println("安装家电!"); } public void installKitchenToilet(){ System.out.println("安装厨卫!"); } public void installFurniture(){ System.out.println("安装家具!"); } public void beautifyOrnament(){ System.out.println("增添装饰品!"); } public void bedclothes(){ System.out.println("添置床上用品!"); } public void buyOthers(){ System.out.println("购置其他家用!"); } }