适配器模式实例
问题描述:
现在要在DrawCircle 中调用DrawAngle 的方法,可是类已经分发出去了,不能修改,如何用适配器模式解决这个问题,画出类关系图并说明采用的是哪种适配器模式?
DrawCircle类:
public class DrawCircle{
public void DrawCircle() {
}
public void insert(String msg){
System.out.println("DrawCircle insert():"+msg);
}
}
DrawAngle类:
public class DrawAngle{
public void DrawAngle() {
}
public void insert(String msg){
System.out.println("DrawAngle insert():"+msg);
}
}
类关系图:
DrawAdapter类:
package com.shipei;
public class DrawAdapter extends DrawCircle {
private DrawAngle drawAngle;
public DrawAdapter(){
drawAngle=new DrawAngle();
}
public void insert(String str){
drawAngle.insert(str);
}
}
测试类:
public class testAdapter {
@Test
public void testDraw(){
DrawCircle draw = new DrawAdapter();
draw.insert("复用");
}
}
运行结果:
总结:通过适配器可以将两个不相干的类联系到一起