适配器模式(Adapter)

适配器模式git

一.适配器模式

1.1 定义

  • 将一个接口转换成客户但愿的另外一个接口.

1.2 角色

  1. 目标接口对象(Target):客户但愿的另外一个接口或具体类.
  2. 须要适配的类(Adaptee):现有的,不符合客户需求的接口或具体类.
  3. 适配器对象(Adapter):包装适配的对象,转换接口.

1.3 实现方式

  1. 类适配器(继承).
  2. 对象适配器(聚合).

二. 具体实现

2.1 建立目标接口及实现类

public interface ITarget {
        void show();
    }
    public class Target implements ITarget{
        public Target(){
            System.out.println("create target...");
        }
        @Override
        public void show() {
            System.out.println(this.getClass().getSimpleName());
        }
    }

2.2 建立须要适配的接口及实现类

public interface IAdaptee {
    }
    public class Adaptee implements IAdaptee{
    }

2.3 类适配器

public class Adapter1 implements IAdaptee{
        ITarget target;
        public ITarget convert(IAdaptee adaptee){
            if(adaptee != null){
                target = new Target();
            }
            return target;
        }
    }

2.4 对象适配器

public class Adapter2 implements ITarget,IAdaptee{
        @Override
        public void show() {
            System.out.println(this.getClass().getSimpleName());
        }
    }

2.5 调用

public static void main(String[] args) {
        Adapter1 adapter1 = new Adapter1();
        ITarget target = adapter1.convert(new Adaptee());
        target.show();

        Adapter2 adapter2 = new Adapter2();
        adapter2.show();
    }

2.6 输出

create target...
    Target
    Adapter2

三. 优缺点

3.1 优势

  • 灵活性好,提升了类的复用度.

3.2 缺点

  • 过多使用会使系统杂乱.

四. 源码

https://github.com/Seasons20/DisignPattern.git

ENDgithub

相关文章
相关标签/搜索