我们经常碰到要将两个没有关系的类组合在一起使用,第一解决方案是:修改各自类的接口,但是如果我们没有源代码,或者,我们不愿意为了一个应用而修改各自的接口,就使用适配器类。
优点:更好的复用性,更好的扩展性,
缺点:过多使用,容易产生零乱,无法整体进行把握
何时使用:你想使用一个类,但是他不符合你现在的接口定义;如果你想创建一个可以重复使用的类,这个类和其它类不兼容;
Code:
接口:Writer
public interface Writer {
public void writerFile();
}
接口Writer的实现类:WriterImpl
public class WriterImpl implements Writer {
@Override
public void writerFile() {
System.out.println("向文件中写内容!");
}
}
接口:Database
public interface Database {
public void insertFile();
}
接口Database实现类:DatabaseImpl
<pre name="code" class="html">public class Database {
public void insertFile(){
<span style="white-space:pre"> </span>System.out.println("向数据库中插入文件!");
<span style="white-space:pre"> </span>}<span style="white-space:pre"> </span>
}
测试类:Test
public class Test {
public static void main(String[] args) {
//Writer w = new WriterImpl();
//w.writerFile();
//Database d = new DatabaseImpl();
//d.insertFile();
Writer w = new Adapter(new DatabaseImpl());
w.writerFile();
}
}
适配器类:Adapter
public class Adapter implements Writer {
Database db;
public Adapter(DatabaseImpl db){
this.db = db;
}
@Override
public void writerFile() {
// TODO Auto-generated method stub
db.insertFile();
}
}