• 设计模式之适配器模式 Adapter


    从现在开始,将转入设计模式中的结构型模式

    定义与角色

    工作场景

    代码实现

    /**
     * 被适配的类--相当于键盘
     * @author bzhx
     * 2017年3月10日
     */
    public class Adaptee {
    
        public void request(){
            System.out.println("可以完成客户请求的需要的功能");
        }
        
    }
    Adaptee类
    public interface Target {
        void handleReq();
    }
    Target 接口
    /**
     * 适配器(类适配器方式)--相当于usb转接器
     * @author bzhx
     * 2017年3月10日
     */
    public class Adapter extends Adaptee implements Target{
    
        @Override
        public void handleReq() {
            super.request();
        }
    
    }
    适配器类Adapter
    /**
     * 适配器(对象适配器,使用了组合方式跟被适配对象整合)--相当于usb转接器
     * @author bzhx
     * 2017年3月10日
     */
    public class Adapter2 implements Target{
    
        private Adaptee adaptee;
        
        @Override
        public void handleReq() {
            adaptee.request();
        }
    
        public Adapter2(Adaptee adaptee) {
            super();
            this.adaptee = adaptee;
        }
        
    }
    适配器类 Adapter2
    /**
     * 客户端类----相当于笔记本,只有usb接口
     * @author bzhx
     * 2017年3月10日
     */
    
    public class Client {
    
        public void test1(Target t){
            t.handleReq();
        }
        
        public static void main(String[] args) {
            Client c = new Client();
            Adaptee a = new Adaptee();
            
            Target t = new Adapter();
            c.test1(t);
        }
    }
    调用1
    /**
     * 客户端类----相当于笔记本,只有usb接口
     * @author bzhx
     * 2017年3月10日
     */
    
    public class Client2 {
    
        public void test1(Target t){
            t.handleReq();
        }
        
        public static void main(String[] args) {
            Client2 c = new Client2();
            Adaptee a = new Adaptee();
            
            Target t = new Adapter2(a);
            c.test1(t);
        }
    }
    调用2
  • 相关阅读:
    java IO输入输出流实现文本复制
    java HashMap
    java TreeSet 实现存自定义不可重复数据
    java中的ArrayList 使得集合中的对象不重复
    java 多线程执行过程
    final关键字的使用
    java中==和equals的区别
    java面向对象理解
    java语言基础(变量和运算符)
    学习Java第一天,大致了解
  • 原文地址:https://www.cnblogs.com/qingdaofu/p/7472713.html
Copyright © 2020-2023  润新知