全部设计模式、设计原则示例和说明,项目目录结构:
java设计模式项目代码地址:
GitHub - yangzeng1211/designPattern: java设计模式
装饰模式:
这种设计模式是指在一个类的基础上增加一个装饰类(也叫包装类),并在装饰类中增加一些新的特性和功能。这样,通过对原有类的包装,就可以在不改变原有类的情况下为原有类增加更多的功能。
/** * @author yz * @date 2022/10/17 11:28 */ public interface Phone { // 接电话 String callIn(); // 打电话 Boolean callOut(String info); }
/** * @author yz * @date 2022/10/17 11:29 */ public class TelePhone implements Phone { @Override public String callIn() { System.out.println("接收语音。。。"); return "get info"; } @Override public Boolean callOut(String info) { System.out.println("发送语音:"+info); return true; } }
/** * 对Phone进行装饰,添加录音功能 * * @author yz * @date 2022/10/17 11:31 */ public class PhoneRecordDecorator implements Phone { private Phone decoratorPhone; public PhoneRecordDecorator(Phone decoratorPhone) { this.decoratorPhone = decoratorPhone; } @Override public String callIn() { System.out.println("启动录音。。。"); String info = decoratorPhone.callIn(); System.out.println("结束录音并保存录音文件。。。"); return info; } @Override public Boolean callOut(String info) { System.out.println("启动录音"); Boolean result = decoratorPhone.callOut(info); System.out.println("结束录音并保存录音文件"); return result; } }
测试:
public static void main(String[] args) { System.out.println("--原有Phone无录音功能--"); Phone phone = new TelePhone(); phone.callOut("Hello,this is TelePhone"); System.out.println(); System.out.println("--经过装饰后的Phone有录音功能--"); PhoneRecordDecorator decorator = new PhoneRecordDecorator(phone); decorator.callOut("Hello,this is 装饰后的 TelePhone"); System.out.println(); }
装饰模式效果有点类似代理模式。两者区别:
装饰模式:侧重给一个实现类动态添加功能,不会对实现类的方法进行过滤拦截
代理模式:侧重将一个实现类的功能,委托给代理类来处理,可以对实现类的方法进行过滤拦截