在不修改原先對象核心的功能的狀況下,對功能進行加強。java
2.經過裝飾模式,將方法加強。如圖架構
car :被裝飾的抽象類ide
package javadesign.decorate; /** * 抽象小汽車 */ public interface Car { public void buildCar(); }
benCar:被裝飾的實現測試
package javadesign.decorate; public class BenCar implements Car { @Override public void buildCar() { System.out.println("建造一輛車"); } }
Decorator:裝飾的類ui
package javadesign.decorate; public class Decorator implements Car { public Car car; public Decorator(Car car){ this.car=car; } @Override public void buildCar() { this.car.buildCar(); } }
StrongDecorator:裝飾的實現
package javadesign.decorate; public class Decorator implements Car { public Car car; public Decorator(Car car){ this.car=car; } @Override public void buildCar() { this.car.buildCar(); } }
Client:測試類this
package javadesign.decorate; public class Client { public static void main(String[] args) { Car car=new BenCar(); Decorator decorator=new StrongDecorator(car); ((StrongDecorator) decorator).buildSportsCar(); ((StrongDecorator) decorator).buildHouseCar(); } }
測試結果:spa
總結:裝飾模式在不改變原先核心功能的狀況下,能夠實現加強,而且不會產生不少繼承類,按照業務模塊劃分,經過不一樣的方法進行裝飾。3d