<>强适配器模式>强劲的主要作用是在新接口和老接口之间进行适配,通过将一个类的接口转换成客户期望的另一个接口,让原本不兼容的接口可以合作无间,本文以实例解析Java设计模式编程中的适配器模式使用,需要的朋友可以参考下
平时我们会经常碰到这样的情况,有了两个现成的类,它们之间没有什么联系,但是我们现在既想用其中一个类的方法,同时也想用另外一个类的方法。有一个解决方法是,修改它们各自的接口,但是这是我们最不愿意看到的。这个时候<强>适配器模式>强就会派上用场了。
p比;适配器模式也叫适配器模式,是由GoF提出的23种设计模式的一种.Adapter模式是构造型模式之一,通过适配器模式,可以改变已有类(或外部类)的接口形式。
适配器模式有三种方式,一种是对象适配器,一种是类适配器,一种是接口适配器
<强>以下举例说明:强>
<强> 1。类适配器强>
公开课DrawRectangle{//画方
公共空间drawRectangle(字符串味精){
system . out。println(“画矩形:“+味精);
}
}
公共接口IDrawCircle{//画圆的接口
空白drawCircle ();
}/* *
*类适配器使用对象继承的方式,是静态的定义方式
* @author石头
*
*/公共类DrawAdapter4Class DrawRectangle延伸实现IDrawCircle{//既能画方又能画圆
@Override
公共空间drawCircle () {
system . out。println (“DrawAdapter4Class: drawCircle”);
}
}
<强> 2。对象适配器强>
/* * *对象适配器:使用对象组合的方式,是动态组合的方式。 *既能画方又能画圆 * @author石头 * DrawAdapter是适配器,DrawRectangle属于适配器,是被适配者,适配器将被适配者和适配目标(DrawCircle)进行适配 * */公共类DrawAdapter4Object实现IDrawCircle{//既能画方又能画圆 私人DrawRectangle DrawRectangle; 公共DrawAdapter4Object (DrawRectangle DrawRectangle) { 这一点。drawRectangle=drawRectangle; } @Override 公共空间drawCircle () { system . out。println (“DrawAdapter4Object: drawcircle”); } 公共空间drawRectangle(字符串味精){ drawRectangle.drawRectangle(味精); } }
<强> 3。接口适配器强>
/* *接口适配器:接口中有抽象方法,我们只想实现其中的几个,不想全部实现, *所以提供一个默认空实现,然后继承自它,重写实现我们想实现的方法 */公共接口IDraw { 空白drawCircle (); 空白drawRectangle (); }/* *接口适配器的默认实现 */公共类DefaultDrawAdapter实现IDraw{//画方画圆皆为空实现 @Override 公共空间drawCircle () { } @Override 公共空间drawRectangle () { 公共类测试{ 公共静态void main (String [] args) {//对象适配器 DrawAdapter4Object objAdapter=new DrawAdapter4Object(新DrawRectangle ()); objAdapter.drawCircle (); objAdapter。drawRectangle (“DrawAdapter4Object”); System.out.println (“- - - - - - - - - - - - - - - -”);//类适配器 DrawAdapter4Class clzAdapter=new DrawAdapter4Class (); clzAdapter.drawCircle (); clzAdapter。drawRectangle (“DrawAdapter4Class”); System.out.println (“- - - - - - - - - - - - - - - -”);//接口适配器 MyDrawAdapter MyDrawAdapter=new MyDrawAdapter (); myDrawAdapter.drawCircle (); myDrawAdapter.drawRectangle (); } 静态类MyDrawAdapter延伸DefaultDrawAdapter { @Override 公共空间drawCircle () { system . out。println (“MyDrawAdapter drawCircle”); } } }
<>强打印强>
DrawAdapter4Object: drawcircle 画矩形:DrawAdapter4Object -------------- DrawAdapter4Class: drawCircle 画矩形:DrawAdapter4Class -------------- 在MyDrawAdapter drawCircle
<>强适配器模式的三个特点:强>
1适配器对象实现原有接口
2适配器对象组合一个实现新接口的对象(这个对象也可以不实现一个接口、只是一个单纯的对象)