装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
装饰模式的优点:
- 装饰模式与继承关系的目的都是要拓展对象的功能,但是装饰模式可以提供比继承更多的灵活性。装饰模式允许系统动态决定“贴上”一个需要的“装饰”,或者“除掉”一个不需要的“装饰”。继承关系则不同,继承关系是静态的,它在系统运行前就决定了。
- 通过不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出更多不同行为的组合。
装饰模式的缺点:
- 由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使设计比较易于进行。但是,在另外一方面,使用装饰模式会产生比使用继承关系所产生的更多的对象。而更多的对象会使得查找错误更为困难,特别是这些对象在看上去极为相似的时候
1.建筑接口
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:04 2019/9/9 */ public interface Building { void bulid(); }
2.高层建筑
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:05 2019/9/9 */ public class HighBuilding implements Building { @Override public void bulid() { System.out.println("build high building"); } }
3.低层建筑
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:06 2019/9/9 */ public class Cottage implements Building { @Override public void bulid() { System.out.println("bulid cottage"); } }
4. 抽象装饰类
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:07 2019/9/9 * * //装饰类 */ public abstract class BuildDecorator implements Building { protected Building building; public BuildDecorator(Building building) { this.building = building; } @Override public void bulid() { building.bulid(); } }
5.高层和低层的抽象装饰类
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:11 2019/9/9 */ public class HighestDecorator extends BuildDecorator { public HighestDecorator(Building building) { super(building); } @Override public void bulid() { building.bulid(); System.out.println("It is highest building"); } }
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:11 2019/9/9 */ public class LowestDecorator extends BuildDecorator { public LowestDecorator(Building building) { super(building); } @Override public void bulid() { building.bulid(); System.out.println("It is lowest building"); } }
6.测试类
package com.design.demo.decorator; /** * @author: GuanBin * @date: Created in 上午12:14 2019/9/9 */ public class DecoratorPatternDemo { public static void main(String[] args) { //高层建筑的修饰类 BuildDecorator highDecorator = new HighestDecorator(new HighBuilding()); //低层建筑的修饰类 BuildDecorator lowDecorator = new LowestDecorator(new Cottage()); highDecorator.bulid(); lowDecorator.bulid(); } }
7.输出
build high building It is highest building bulid cottage It is lowest building Process finished with exit code 0