Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

适配器模式 #221

Open
louzhedong opened this issue Jun 18, 2020 · 0 comments
Open

适配器模式 #221

louzhedong opened this issue Jun 18, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

适配器模式

将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作

适配器模式是一种亡羊补牢的模式

优点:

可以让两个毫无关系的类在一起运行

增加类的透明性

提高类的复用性

灵活性好

实现
Java
/**
 * 目标角色
 **/
public interface Target {
    void request();
}

public class ConctreteTarget implements Target{
    @Override
    public void request() {

    }
}

/**
 * 源角色
 **/
public class Adaptee {
    public void doSomething(){}
}

/**
 * 适配器角色
 **/
public class Adapter extends Adaptee implements Target{
    @Override
    public void request() {
        super.doSomething();
    }
}

public class Client {
    public static void main(String[] args) {
        // 原有业务
        Target target = new ConctreteTarget();
        target.request();

        // 加入适配器后业务
        Target adapter = new Adapter();
        adapter.request();
    }
}
JavaScript
var getGuangdongCity = function () {
  var guangdongCity = [
    {
      name: 'dongguan',
      id: 11
    },
    {
      name: 'guangzhou',
      id: 12
    }
  ];

  return guangdongCity;
}

// 新的数据结构
var guangdongCity = {
  dongguan: 11,
  guangzhou: 12
}

// 增加一个适配器,来做一层转换
var addressAdapter = function (oldAddressFn) {
  var address = {};
  var oldAddress = oldAddressFn();
  for (var i = 0, c; c = oldAddress[i++];) {
    address[c.name] = c.id;
  }

  return function () {
    return address;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant