现在的位置: 首页 > 综合 > 正文

适配器(Adapter)模式

2013年10月17日 ⁄ 综合 ⁄ 共 2337字 ⁄ 字号 评论关闭
适配器模式:
在软件系统中,由于应用环境的变化,常常需要将“一些现存的对象”放在新的环境中应用,但是新环境要求的接口是这些现存对象所不满足的。那么如何应对这种“迁移的变化”?如何既能利用现有对象的良好实现,同时又能满足新的应用环境所要求的接口?这就是本文要说的Adapter模式。 
使用意图:
将一个类的接口转换成客户希望的另外一 个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作 。
适配器模式的构成:
 • 目标抽象角色(Target ) 
     – 定义客户要用的特定领域的接口 
 • 适配器(Adapter ) 
     – 调用另一个接口,作为一个转换器 
 • 适配器(Adaptee ) 
     – 定义一个接口,Adapter需要接入 
 • 客户端(Client) 
     – 协同对象符合Adapter适配器 
 
适用性:
1)、对象需要利用现存的并且接口不兼容的类 。 
2)、需要创建可重用的类以协调其他接口可能不兼容的。 
有三种类型的适配器模式 
     – 类适配器(采取继承的方式) 
     – 对象适配器(采取对象组合的方式)推荐 
     – 缺省的适配器模式(在UI中的Awt和Swing事件中所采用比较多的模式)

实现简单的适配器案例:
1).采取继承的方式实现
目标抽象角色(Target )
public interface Target {
	public void method1();
}
适配器(Adaptee )
public class Adaptee {
	public void method2() {
		System.out.println("目标方法被调用");
	}
}
适配器(Adapter )
public class Adapter extends Adaptee implements Target { 
	@Override
	public void method1() {
		this.method2();
	} 
}
客户端(Client) 
public class Client {
	public static void main(String[] args) {
		Target target = new Adapter();
		target.method1();
	}
}
执行结果 目标方法被调用
2).采用对象组合的方式(只需要修改两个地方):
适配器(Adapter )
public class Adapter implements Target {
	private Adaptee adaptee; 
	public Adapter(Adaptee adapter) {
		this.adaptee = adapter;
	}
	@Override
	public void method1() {
		this.adaptee.method2();
	}
}
客户端(Client)
public class Client {
	public static void main(String[] args) { 
		Target target = new Adapter(new Adaptee());
		target.method1();
	}
}
3)缺省的适配器模式(当只需要某个接口中的某一个方法的时候,采用这种模式)
适配器接口
public interface Service {
	public void method1();
	public void method2();
	public void method3();
}
接口实现
package org.ml.adapter.qs;

public class ServicerAdapter implements Service {
	@Override
	public void method1() {
	}
	@Override
	public void method2() {
	}
	@Override
	public void method3() {
	}
}
假设只需要接口的
method2()方法
public class NeedService extends ServicerAdapter {

	@Override
	public void method2() {
		System.out.println("采用了缺省适配器模式调用方法");
	}
}

缺省用例:

package org.ml.adapter.qs;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class Main {
	JFrame frame = new JFrame();

	public Main() {
		frame.setSize(500, 300);
		frame.setVisible(true);
		// 鼠标动作监听
		frame.addMouseMotionListener(new MouseAdapter() {
			// 在此处采用适配器模式,只需要mouseMoved方法
			@Override
			public void mouseMoved(MouseEvent e) {
				System.out.println("(x:" + e.getX() + ",y:" + e.getY() + ")");
			}
		});
		
		frame.addWindowListener(new WindowAdapter() {
			// 同样,此处也采用适配器模式,只需要调用windowClosing方法
			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("窗口现在已经关闭");
				System.exit(0);
			}
		});
	}

	public static void main(String[] args) {
		new Main();
	}
}

抱歉!评论已关闭.