zoukankan      html  css  js  c++  java
  • 设计模式之适配器模式

    适配器模式

    将一个类的接口转换为客户希望的另外一个接口,适配器模式使得原本由于不兼容而不能一起工作的类可以一起工作。

     Target

    package com.hml.adapter;
    
    public class Target {
    
        public void request() {
            System.out.println("普通请求");
        }
    }

    Adaptee

    package com.hml.adapter;
    
    public class Adaptee {
    
        public void spacificRequest() {
            System.out.println("特殊请求");
        }
    }

    Adapter

    package com.hml.adapter;
    
    public class Adapter extends Target {
    
        private Adaptee adaptee = new Adaptee();
    
        @Override
        public void request() {
            adaptee.spacificRequest();
        }
    
    }

    Test

    package com.hml.adapter;
    
    public class Test {
    
        public static void main(String[] args) {
            Target target = new Adapter();
            target.request(); 
        }
    }

    类图

    系统的数据和行为都正确,但是接口不符合,我们应该考虑用适配器模式,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些存在的类,但是接口又与复用环境要求不一致的情况。适配器模式有两种,类适配器和对象适配器,类适配器是通过多重继承对一个接口与另一个接口进行匹配。适配器的使用时机一般在后期维护时使用,如果在设计初期应该考虑更改设计。

  • 相关阅读:
    flex 弹性盒布局 移动端首页
    less+rem基础使用
    github 本地操作
    git 码云
    react基础知识
    css样式
    uni-app 知识点
    web app
    2019年一半已过,这些大前端技术你都GET了吗?- 下篇
    2019年大前端技术周刊-#31周
  • 原文地址:https://www.cnblogs.com/heml/p/4638911.html
Copyright © 2011-2022 走看看