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();
        }
    }

    输出内容为:

  • 相关阅读:
    h5-7
    h5-6
    h5-5
    h5-4
    h5-3
    h5-2
    return
    字符串的常用操作
    字符串中的转义字符
    字典的统计,合并,清空操作
  • 原文地址:https://www.cnblogs.com/mutong1228/p/10183318.html
Copyright © 2011-2022 走看看