设计模式-适配器模式

本文介绍了适配器模式的定义及其在Java中的应用,通过一个实例展示了如何创建并测试适配器模式。同时,文章还探讨了装饰器模式,详细解释了装饰器模式的实现步骤,并通过测试类展示其功能,如添加美颜和滤镜效果。适配器模式和装饰器模式结合使用,实现了功能的增强和接口的兼容。

1.背景:

        碰上金九银十了,猛刷一下设计模式,记录一下适配器模式的学习

2. 适配器模式定义:

        将一个类的接口转换成客户希望的另一个接口,adapter模式使的原来由于接口不兼容而不能一起工作的那些类可以一起工作;

3.懒汉-适配器开发流程几个问题:

        1. 适配器模式如何创建并测试?

       

3.1 适配器模式如何创建并测试

1.定义接口Component

interface Component{
    void operation();
}

2. 实现接口Component

class ConcreateComponent implements  Component{

    @Override
    public void operation() {
        System.out.println("拍照");
    }
}

3. 定义抽象类实现Component

abstract class Decorator implements Component{
    Component component;
    public Decorator(Component component){
        this.component = component;
    }
}

4. 定义ConcreateDecorator类继承Decorator

class ConcreateDecorator extends Decorator{

    public ConcreateDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("添加美颜");
        component.operation();
    }
}

5. 定义ConcreateDecorator2类继承Decorator

class ConcreateDecorator2 extends Decorator{

    public ConcreateDecorator2(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("添加滤镜");
        component.operation();
    }
}

6. 测试类

/**
 * 装饰器模式
 */
public class DecoratorTest {

    public static void main(String[] args) {
//        Component component = new ConcreateComponent();
//        component.operation();

//        Component component = new ConcreateDecorator(new ConcreateComponent());
//        component.operation();

        Component component = new ConcreateDecorator2(new ConcreateDecorator(new ConcreateComponent()));
        component.operation();
    }
}

测试结果:

添加滤镜
添加美颜
拍照

 总结:功能已全部添加上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bingtanghulu_6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值