zoukankan      html  css  js  c++  java
  • java 适配器模式(adapter pattern)

    适配器就是一种适配中间件,它存在于不匹配的二者之间,用于连接二者,将不匹配变得匹配。

    场景:电脑读取内存卡中的内容,内存卡是没有办法直接插在电脑的USB接口上,那就不需要一个转换器。

    下面的例子实现了上述的功能

    /**
     * @author liusongwei
     * @Title: MemoryCard
     * @ProjectName demohystrix
     * @Description: 定义一个内存卡接口
     * @date 2018/12/279:15
     */
    public interface MemoryCard {
        public String novel();
    }
    package com.example.demohystrix.designpattern.structure.adapter;
    
    /**
     * @author liusongwei
     * @Title: MemoryCardImpl
     * @ProjectName demohystrix
     * @Description: 实现内存卡接口并编写内存中的内容
     * @date 2018/12/279:18
     */
    public class MemoryCardImpl implements MemoryCard {
        @Override
        public String novel() {
            System.out.println("开始读取小说中的内容");
            return "盘古开天辟地,名曰《斗鱼》";
        }
    }
    package com.example.demohystrix.designpattern.structure.adapter;
    
    /**
     * @author liusongwei
     * @Title: Computer
     * @ProjectName demohystrix
     * @Description: 定义一个电脑接口
     * @date 2018/12/279:17
     */
    public interface Computer {
        public void read();
    }
    package com.example.demohystrix.designpattern.structure.adapter;
    
    /**
     * @author liusongwei
     * @Title: Adapter
     * @ProjectName demohystrix
     * @Description: 实现一个电脑接口的适配器,并读取内存卡中的内容
     * @date 2018/12/279:20
     */
    public class Adapter implements Computer {
        private MemoryCard memoryCard;
    
        public Adapter(MemoryCard memoryCard){
            this.memoryCard = memoryCard;
        }
        @Override
        public void read() {
            String str = memoryCard.novel();
            System.out.println("读取的内容为:" + str);
        }
    }
    package com.example.demohystrix.designpattern.structure.adapter;
    
    /**
     * @author liusongwei
     * @Title: Demo
     * @ProjectName demohystrix
     * @Description: TODO
     * @date 2018/12/279:22
     */
    public class Demo {
        public static void main(String[] args){
            Computer computer = new Adapter(new MemoryCardImpl());
            computer.read();
        }
    }

    输出内容为:

  • 相关阅读:
    Android自定义控件之仿美团下拉刷新
    Android性能优化之Bitmap的内存优化
    基于openfire+smack即时通讯instant message开发
    Android各组件/控件间通信利器之EventBus
    android的task任务栈
    Activity的启动模式
    Android 自定义View (一)
    Android之Handler用法总结
    Android中轻松使用线程
    Android 中Activity,Window和View之间的关系
  • 原文地址:https://www.cnblogs.com/mutong1228/p/10183318.html
Copyright © 2011-2022 走看看