(原创)认识设计模式-适配器

2015/03/13 设计模式

介绍

img

适配器的定义为:将一个接口转变成客户端所期望的另一种接口,从而使原本因接口不匹配的两个类能在一起工作。

适配器模式恰如其名,就是来适配各种接口的,类似生活中的插线板,买了一个家电,发现是三脚插头,墙上的电源却是两脚座子,一般情况下,我们都会再买一个插线板,利用插线板来转换一下,这里的插线板其实就是典型的适配器。

使用方式

	public interface Target {
	
	    public void request();
	    
	}
	
	public class Adapter implements Target{
	
	    private Adaptee mAdaptee = new Adaptee();
	
	    @Override
	    public void request() {
	        mAdaptee.doSomething();
	    }
	
	}
	
	public class Adaptee {
	
	    public void doSomething()
	    {
	        System.out.println("Adaptee doSomething ");
	    }
	    
	}


	public class Main {
	
	    public static void main(String[] args) throws Exception {
	
	        Target target = new Adapter();
	        System.out.println("target request ");
	        target.request();
	
	    }
	}

结果如下:

target request 
Adaptee doSomething 

总结

适配器模式其实是面对扩展需求的一种补救措施,在框架设计时期应该避免出现这个模式,等产品成型后面对新增的需求,为了不影响原有的框架和稳定性可以采用这种模式,模式使用也很简单,就是对接口做一个转换。


知识共享许可协议
本作品采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

站内搜索

    撩我备注-博客

    joinee

    目录结构