适配器模式

适配器模式

  • 适配器模式将某个类的接口转换成客户端期望的另一个接口表示,类别如下:
类适配器
  • 数据源类Source,目标接口 Target, 适配器类 Adapter ,Adapter类继承Source类,并且实现Target接口,在Adapter类中实现数据的转换,类图如下:
    在这里插入图片描述

  • 实现代码如下:

    open class Source {
    protected fun soureMethod() {
        System.out.println("source")
         }
    }
    
    interface Target {
     fun targetMethod()
    }
    
    class Adapter : Source(), Target {
     override fun targetMethod() {
        System.out.println("target")
        System.out.println("call sourceMethod")
        soureMethod()
         }
     }
    
    fun main(args: Array<String>) {
        val target = Adapter()
         target.targetMethod()
    }
    
对象适配器
  • 基本思路和类的适配器模式相同,只是将Adapter类作修改,这次不继承Source类,而是持有Source类的实例.类图如下:
    在这里插入图片描述

  • 实现代码如下:

    class Source {
        fun soureMethod() {
        System.out.println("source")
         }
    }
    
    interface Target {
        fun targetMethod()
    }
    
    class Adapter : Target {
        override fun targetMethod() {
            System.out.println("target")
            System.out.println("call sourceMethod")
            Companion.source.soureMethod()
        }
    
        fun setSource(source: Source): Adapter {
            Companion.source = source
            return this
        }
    
        companion object {
            private lateinit var source: Source
        }
    }
    
    
    fun main(args: Array<String>) {
        val source = Source()
        val target = Adapter().setSource(source)
        target.targetMethod()
    }
    
    
接口适配器
  • 当一个接口中有多个方法时,某些类只需要实现其中一部分方法,此时我们可以定义一个抽象类实现该接口,然后其他类继承该抽象类,重写需要的方法即可。类图如下:
    在这里插入图片描述

  • 代码实现如下:

    interface Source {
        fun method1()
        fun method2()
        fun method3()
        fun method4()
    }
    
    abstract class Adapter : Source {
        override fun method1() {}
        override fun method2() {}
        override fun method3() {}
        override fun method4() {}
    }
    
    class Target1 : Adapter() {
        override fun method1() {
            System.out.println("Target1+method1")
        }
    
        override fun method2() {
            System.out.println("Target1+method2")
        }
    }
    
    class Target2 : Adapter() {
        override fun method3() {
            System.out.println("Target2+method3")
        }
    
        override fun method4() {
            System.out.println("Target2+method4")
        }
    }
    
    fun main(args: Array<String>) {
        val t1 = Target1()
        val t2 = Target2()
        t1.method1()
        t1.method2()
        t2.method3()
        t2.method4()
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值