java设计模式

全部设计模式、设计原则示例和说明,项目目录结构:

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();

}

装饰模式效果有点类似代理模式。两者区别:

装饰模式:侧重给一个实现类动态添加功能,不会对实现类的方法进行过滤拦截

代理模式:侧重将一个实现类的功能,委托给代理类来处理,可以对实现类的方法进行过滤拦截

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值