适配器模式
介绍
在软件设计中,为了解决接口不一致的问题,两个软件模块之间往往也需要通过一个适配器类Adapter进行是适配。这样的模式叫做适配器设计模式。
适配器模式分为两种,一种是类适配器,一种是对象适配器模式。
(1)类适配器
(2)对象适配器
示例
现在有一个类student,现在要在要添加一个功能read();
类适配器
class student
{
public String getAge(){...}
public String getName(){...}
public void run(){...}
}
public interface student_add
{
public abstract String getAge();
public abstract String getName();
public abstract void run();
public abstract void read();
}
适配器
class studentAdapter extends student implements student_add
{
public void read()
{
....
}
}
对象适配器
class student
{
public String getAge(){...}
public String getName(){...}
public void run(){...}
}
public interface student_add
{
public abstract String getAge();
public abstract String getName();
public abstract void run();
public abstract void read();
}
适配器
class studentAdapter implements student_add
{
student s;
public void read()
{
....
}
public String getAge(){s.getAge();}
public String getName(){s.getName();}
public void run(){s.run();}
}
类适配器与对象适配器的区别是:
类适配器模式对被适配对象采用了继承,而对象适配器对被适配对象采用的则是调用。