适配器模式
- 主要目标是将已有的类(不方便改动的),通过适配器模式,适应新的接口.
public interface ChinaSheep {
void sound();
}
class RedSheep implements ChinaSheep {
@Override
public void sound() {
System.out.println("我是中国红色的羊");
}
}
class WhiteSheep implements ChinaSheep {
@Override
public void sound() {
System.out.println("我是中国白色的羊");
}
}
class Man{
public void callSheep(ChinaSheep... chinaSheeps){
for (ChinaSheep chinaSheep : chinaSheeps) {
chinaSheep.sound();
}
}
}
public static void main(String[] args) {
Man man = new Man();
RedSheep redSheep = new RedSheep();
WhiteSheep whiteSheep = new WhiteSheep();
man.callSheep(redSheep,whiteSheep);
}
- 上述代码描述现有的系统,Man类只能召唤中国的羊,此时,引进了一群外国羊, 外国羊有自己的接口,叫做shout(),外国羊无法修改了,通过适配器模式改造外国羊来适配现有的系统
class ForeignRedSheep implements ForeignSheep {
@Override
public void shout() {
System.out.println("我是外国红色的羊");
}
}
class ForeignWhiteSheep implements ForeignSheep {
@Override
public void shout() {
System.out.println("我是外国白色的羊");
}
}
- 此时适配器有两种写法,一种持有对象的引用,一种是继承
class ForeignRedSheepAdapter extends ForeignRedSheep implements ChinaSheep{
@Override
public void sound() {
shout();
}
}
class ForeignWhiteSheepAdapter implements ChinaSheep{
private ForeignSheep foreignSheep;
public ForeignWhiteSheepAdapter(ForeignSheep foreignSheep) {
this.foreignSheep = foreignSheep;
}
@Override
public void sound() {
foreignSheep.shout();
}
}
public static void main(String[] args) {
Man man = new Man();
RedSheep redSheep = new RedSheep();
WhiteSheep whiteSheep = new WhiteSheep();
man.callSheep(redSheep,whiteSheep);
ForeignRedSheepAdapter foreignRedSheepAdapter = new ForeignRedSheepAdapter();
ForeignWhiteSheepAdapter foreignWhiteSheepAdapter = new ForeignWhiteSheepAdapter(new ForeignWhiteSheep());
man.callSheep(foreignRedSheepAdapter,foreignRedSheepAdapter);
}