Adapter模式
意图:将一个无法控制的现有对象与一个特定接口相匹配。
问题:一个系统哦功能拥有正确的数据和行为,但接口却是错误的。
典型用途:你必须把某些东西实现为我们定义或者已经拥有的抽象类的派生接口。
参与者和协作者:Adapter对Adaptee的接口进行适配,使它与Target(Adapter派生自它)相匹配。让Client把Adaptee当作Target的一个类型来使用它。
效果:Adapter模式让现存的对象适应新的类结构,而不受它们的接口限制。
实现:将现存的类包含在另一个类中。包容类与需要的接口相匹配,并调用被包容类的方法。
适配器是将有数据但接口不适配的类适配到可用的实现统一接口的类
这里有篇文章http://www.jdon.com/designpatterns/adapter.htm
我觉得有两种方法实现adapter模式
一种就是类图里面个的,adatper extends target,有adapter实现适配到adatee的过程
另一种是adapter extends 自 adaptee,同时implements target接口,
我现在同时实现一下,让大家看看
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package adapter;
/**
*
* @author blacklaw
*/
public class Adapter {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
PegAdapter adapter;
adapter = new SquareAdapter(new SquarePeg());
adapter.insert();
adapter = new RoundAdapter(new RoundPeg());
adapter.insert();
}
/**
* Adaptee class
*/
static class SquarePeg{
public void insertSquare(){
System.out.println("Square peg insert");
}
}
/**
* Adaptee class
*/
static class RoundPeg{
public void insertRound(){
System.out.println("Round peg insert");
}
}
abstract class PegAdapter{
abstract void insert();
}
static class SquareAdapter extends PegAdapter{
private SquarePeg square;
SquareAdapter(SquarePeg s){
this.square = s;
}
@Override
void insert() {
square.insertSquare();
}
}
static class RoundAdapter extends PegAdapter{
private RoundPeg round;
RoundAdapter(RoundPeg r){
this.round = r;
}
@Override
void insert() {
round.insertRound();
}
}
}
第二种用接口实现
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package adapter;
/**
*
* @author blacklaw
*/
public class Adapter1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
PegAdapter adapter;
adapter = new SquareAdapter();
adapter.insert();
adapter = new RoundAdapter();
adapter.insert();
}
/**
* Adaptee class
*/
static class SquarePeg{
public void insertSquare(){
System.out.println("Square peg insert");
}
}
/**
* Adaptee class
*/
static class RoundPeg{
public void insertRound(){
System.out.println("Round peg insert");
}
}
interface PegAdapter{
public void insert();
}
static class SquareAdapter extends SquarePeg implements PegAdapter{
@Override
public void insert() {
super.insertSquare();
}
}
static class RoundAdapter extends RoundPeg implements PegAdapter{
@Override
public void insert() {
super.insertRound();
}
}
}
相比下来,我觉地用接口实现跟好理解,而且操作简单