本文共 1483 字,大约阅读时间需要 4 分钟。
对原有功能进行增强。装饰模式含有一下几部分。抽象构件、具体构件、抽象装饰、具体装饰。原本功能是具体构件中的功能,现在要通过装饰来对具体构建进行增强。
定义一个接口,来确定他的子类要实现怎样的功能。
package com.wx.demo01;//抽象构建角色public interface Component { public void operation();}
定义具体构件类,实现抽象构件接口,此类就是原本的功能。
package com.wx.demo01;//具体构建角色public class ConcreteComponent implements Component{ public void operation() { System.out.println("调用具体构件角色的方法operation()"); } public ConcreteComponent(){ System.out.println("创建具体构建角色"); }}
现在需要对原本功能进行装饰增强。定义抽象装饰类,实现抽象构件接口。
package com.wx.demo01;//抽象装饰角色public class Decorator implements Component{ private Component component; public Decorator(Component component){ this.component = component; } public void operation() { component.operation(); }}
继承抽象装饰,在具体装饰中添加增加的功能。
package com.wx.demo01;//具体装饰角色public class ConcreteDecorator extends Decorator{ public ConcreteDecorator(Component component) { super(component); } public void operation(){ super.operation(); addedFunction(); } public void addedFunction(){ System.out.println("为具体构件角色增加额外的功能addedFunction()"); }}
package com.wx.demo01;public class DecoratorPattern { public static void main(String[] args) { Component component = new ConcreteComponent(); component.operation(); System.out.println("-----------------------"); Component d = new ConcreteDecorator(component); d.operation(); }}
转载地址:http://zsrdb.baihongyu.com/