java常用设计模式(适配模式)

来源:互联网 发布:ubuntu卸载程序命令 编辑:程序博客网 时间:2024/06/05 21:07

适配模式:分为类的适配模式和对象的适配模式.举个栗子,假如我有一个粗水管cu和一个细xi的水管,我要把他们接在一起,那怎么办呢 ?中间加个接头不就好了吗(zz),这个接头就是适配器.要求适配器也得有一面是细的,一面是粗的,适配器需要有的属性,可以归类成target.

一 类的适配模式:细管子需要粗的管子为它提供细的接口,但是粗的管子并没有这个接口

1:设计target,需要他能同时具备细的接口,又同时有粗的接口

public interface Target {public void isXi();public void isCu();}
2:因为细的管子要连接粗管子(源Adapee)角色:要求它能别细的管子连接。

public class Cu { void haveCu() {System.out.println("我有粗的接口");}}
3:适配器,能同时连接这两根管子,他继承粗水管的属性,又拓展出细管子的功能

public class Adapter extends Cu implements Target{@Overridepublic void isXi() {System.out.println("我提供了细的接口");}@Overridepublic void isCu() {System.out.println("我提供了粗的接口");}}

4:细水管去连接粗水管

public class Xi {public static void main(String[] args) {//需要调用获取细接口的方法,但是粗管子没有这个方法,所以注入适配器对象Adapter adapter  = new Adapter();adapter.isXi();//输出:我提供了细的接口}}

二 对象适配模式:与类的适配器模式不同的是,对象的适配器模式不是使用继承关系连接到Adaptee类,而是使用委派关系连接到粗水管(Adaptee)类。

1:对象的适配,封装Adaptee

public class Adapter_Oriented implements Target{private Cu cu;/** * @param cu */public Adapter_Oriented(Cu cu) {super();this.cu = cu;}@Overridepublic void isXi() {System.out.println("我提供了细的接口");}@Overridepublic void isCu() {System.out.println("我提供了粗的接口");}}
2测试

public static void main(String[] args) {Cu cu = new Cu();Adapter_Oriented adapter_Oriented = new Adapter_Oriented(cu);adapter_Oriented.isXi();//我提供了细的接口}

总结:1,优点 提供了更好的代码复用性,拓展兼容性

        2,缺点  代码不容易阅读,会使系统过于凌乱,过多会引起系统杂乱无章.







原创粉丝点击