智者千虑必有一失,愚者千虑必有一得html
在咱们开发过程当中也会常常碰到一些给原有的系统加一些功能,因此无论前期咱们呢可行性、需求分析和系统设计处理的多好,随着时间的推移,总会出一些“意外”。所以咱们该如何处理掉这些“意外”呢?聪明的程序员们就想到了许多的补救模式,其中适配器模式就是补救模式中的一种。这种模式能够可以让你从由于业务的快速迭代而引起代码改变的烦恼中解脱出来。程序员
将一个类的接口变换成客户端所期待的另外一种接口,从而使本来由于接口不匹配而没法在一块儿工做的两个类可以一块儿工做设计模式
适配器模式有三个角色ide
适配器模式有两种体现形式,一种是经过继承来表现,一种是经过关联对象来表现,下面给演示下继承表现的适配器。设计
下面咱们写一个简单的适配器模式的例子,以下所示code
Target
接口代码htm
interface Target{ public void request(); }
实现了Target
接口的类对象
class RealTarget implements Target{ @Override public void request() { System.out.println("I am Target"); } }
Source
源目标类blog
class Source{ public void doSomething(){ System.out.println("I am Source"); } }
接下来核心的角色要出现了就是Adapter
类继承
class Adapter extends Source implements Target{ @Override public void request() { super.doSomething(); } }
接下来咱们能够进行调用试试
public class AdapterTest { public static void main(String[] args) { Target target = new RealTarget(); target.request(); Target target2 = new Adapter(); target2.request(); } }
打印以下
I am Target I am Source
咱们上面使用的是经过继承来使用适配器模式,还有一种作法就是将原有的继承关系变动为关联关系就能够了。
对象适配器和类适配器的区别在于:类适配器是经过继承来表现的,而对象适配器是对象的合成关系,也能够说是类的关联关系,这是二者的根本区别。两个都会在项目中用到,因为对象适配器是经过类间的关联关系进行耦合的,所以在设计的时候就比较灵活。而类适配器只能经过覆写源角色的方法进行扩展。所以在实际项目中,对象适配器的使用场景比较多。
咱们仍是先来看一下对象适配器的类图以下
而后写一个通用的例子
如今接口Target
interface Target2{ public void printSource1(); public void printSource2(); }
而后有Adapter
class Adapter implements Target{ private Source1 source1; private Source2 source2; public Adapter(){ source1 = new Source1(); source2 = new Source2(); } @Override public void printSource1() { source1.print(); } @Override public void printSource2() { source2.print(); } }
而后两个Source
class Source1{ public void print(){ System.out.println("I am Source1"); } } class Source2{ public void print(){ System.out.println("I am Source2"); } }
而后进行调用以下
public static void main(String[] args) { Target2 target2 = new Adapter2(); target2.printSource1(); target2.printSource2(); }
打印以下
I am Source1 I am Source2
这样在之后增长了需求之后,只须要从新写适配器便可,上层代码不用动。
适配器应用的场景只须要记住一点就够了:当你有动机修改一个已经投产中的接口时,适配器模式是最适合你的模式。好比系统扩展了,须要使用一个已有或者是新建的类,可是这个类又不符合系统的接口,怎么办?这时候就可使用适配器模式。