Mybatis ResolverUtil的设计概念

本文探讨了设计模式中的开放封闭原则,通过实例解析如何在不修改现有代码的情况下,通过扩展实现新的功能。以ResolverUtil类为例,展示了如何利用接口和实现类来达到这一目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设计模式原则之开放-封闭原则

  程序扩展对外开放,修改对外封闭

ResolverUtil

其中有一个接口、两个内部类,Class对象和Annotation对象被封装成了Test对象

Test

两个实现类,核心功能是匹配Class类型

IsA

public static class IsA implements Test {
    private Class<?> parent;

    /** Constructs an IsA test using the supplied Class as the parent class/interface. */
    public IsA(Class<?> parentType) {
      this.parent = parentType;
    }

    /** Returns true if type is assignable to the parent type supplied in the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && parent.isAssignableFrom(type);
    }

    @Override
    public String toString() {
      return "is assignable to " + parent.getSimpleName();
    }
}

AnnotatedWith

public static class AnnotatedWith implements Test {
    private Class<? extends Annotation> annotation;

    /** Constructs an AnnotatedWith test for the specified annotation type. */
    public AnnotatedWith(Class<? extends Annotation> annotation) {
      this.annotation = annotation;
    }

    /** Returns true if the type is annotated with the class provided to the constructor. */
    @Override
    public boolean matches(Class<?> type) {
      return type != null && type.isAnnotationPresent(annotation);
    }

    @Override
    public String toString() {
      return "annotated with @" + annotation.getSimpleName();
    }
}

使用

String packageName = "com/wjz/mybatis/type/scan";
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(CommonService.class), packageName);
Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses();

如此设计

我们可以实现Test接口,传参find方法时传入,而不用修改ResolverUtil的内部方法。

package com.wjz.mybatis.type.scan;

import org.apache.ibatis.io.ResolverUtil.Test;

public class Testtest implements Test {

    @Override
    public boolean matches(Class<?> type) {
        if (type == Testtest.class) {
            return true;
        }
        return false;
    }

}

 

转载于:https://www.cnblogs.com/BINGJJFLY/p/9905198.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值