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

    适配器(Adapter)模式

    把一个类的接口变换成客户端所希望的另一种接口,从而使原本因接口

    原因不匹配而无法工作的两个类能够一起工作。

    适配器(Adapter)模式的构成
    目标抽象角色(Target):定义客户要用的特定领域的接口
    适配器(Adapter):调用另一个接口,作为一个转换器
    适配器(Adaptee):定义一个接口,Adapter需要接入
    客户端(Client):协同对象符合Adapter适配器

    适配器的分类
    有三种类型的适配器模式

    public interface Target {
     public void method1();
    }

    public class Adaptee {
     public void method2(){
      System.out.println("目标方法");
     }
    }


    类适配器(采取继承的方式)

    public class Adapter extends Adaptee implements Target {
     @Override
     public void method1() {
      this.method2();
     }
    }

    public class Client {
     public static void main(String[] args) {
      Target target=new Adapter();
      target.method1();
     }
    }

    对象适配器(采取对象组合的方式)(推荐)

     public class Adapter implements Target{
     private Adaptee adaptee;
     public Adapter(Adaptee adaptee){
      this.adaptee=adaptee;
     }
     @Override
     public void method1() {
      adaptee.method2();
     }
    }

    public class Client {
     public static void main(String[] args) {
      Target target=new Adapter(new Adaptee());
      target.method1();
     }
    }

    缺省的适配器模式(AWT、Swing事件模型所采用的模式)

    public interface AbstractService {
     public void service1();
     public void service2();
     public void service3();
    }

    public class ServiceAdapter implements AbstractService{
     @Override
     public void service1() {
     }
     @Override
     public void service2() {
     }
     @Override
     public void service3() {
     }
    }

    package com.shengsiyuan.pattern.defaultadapter;

    public class ConcreteService extends ServiceAdapter {
     @Override
     public void service1(){
      System.out.println("执行业务方法");
     }
    }

  • 相关阅读:
    工作中常用git命令总结
    工作中,实用map给数组去重的详解
    关于OC中的block自己的一些理解(一)
    存储过程专题(Oracle)
    ORACLE事物隔离级别和脏读、幻读、不可重复读区别
    C#客户端Json转DataTable
    C# Newtonsoft.Json JObject常用方法
    C#中的内部函数(子函数)
    C# Dev GridView当前行
    C#从数据库中加载照片的
  • 原文地址:https://www.cnblogs.com/mingforyou/p/2288018.html
Copyright © 2011-2022 走看看