实施适配器模式

Implementing adapter pattern

这些是我的。java classes。我是否正确实施了适配器模式?

界面播放

public interface Play {

  public void Tune(String Type,String Guitar);

}

advanceTuning 界面

public interface AdvanceTuning {

  public void getSharp(String Guitar);
  public void getLowKey(String Guitar);

}

lowkeytuning.java

public class LowKeyTuning implements AdvanceTuning{

@Override
public void getSharp(String Guitar) {
    // TODO Auto-generated method stub

}

@Override
public void getLowKey(String Guitar) {
    // TODO Auto-generated method stub
    System.out.println(Guitar+": Guitar Tuned to LowKey");
}

}

Guitar.java

 public class Guitar implements Play{

Adapter adapter;
@Override
public void Tune(String Type, String Guitar) {
    // TODO Auto-generated method stub
    if(Type.equalsIgnoreCase("Standard")){
        System.out.println(Guitar+": Guitar Tuned to Standard");
    }
    else if(Type.equalsIgnoreCase("Sharp") || Type.equalsIgnoreCase("LowKey")){

        adapter=new Adapter(Type);
        adapter.Tune(Type, Guitar);
    }
    else{
        System.out.println("No Such Tuning exists as "+Type);
    }
}   
}

Adapter.java

public class Adapter implements Play{

AdvanceTuning aTune;

public Adapter(String Type){

    if(Type.equalsIgnoreCase("Sharp")){

        aTune= new SharpTuning();
    }
    else if(Type.equalsIgnoreCase("LowKey")){
        aTune= new LowKeyTuning();
    }
}

@Override
public void Tune(String Type,String Guitar) {
    // TODO Auto-generated method stub
    if(Type.equalsIgnoreCase("Sharp")){
        aTune.getSharp(Guitar);
    }
    else if(Type.equalsIgnoreCase("LowKey")){
        aTune.getLowKey(Guitar);
    }
}
}

SharpTuning.java 等同于 Lowkey.java

我有一个 client.java class,它创建一个 Guitar.java 的对象并调用它的方法 Tune();

我有几点建议:

移动此代码:

if(Type.equalsIgnoreCase("Sharp")){

        aTune= new SharpTuning();
    }
    else if(Type.equalsIgnoreCase("LowKey")){
        aTune= new LowKeyTuning();
    }

进入某种工厂方法。

static AdvanceTuning create(String string){
 if(Type.equalsIgnoreCase("Sharp")){

            return new SharpTuning();
        }
        else if(Type.equalsIgnoreCase("LowKey")){
return new LowKeyTuning();
        }
}

你的适配器,让它接受的不是字符串,而是 AdvancedTune。那么如果需要的话,您将能够重用现有的曲调。 那么你的构造函数将看起来像那样

public Adapter(AdvanceTuning aTune){
this.aTune=aTune;
}

然后您可以通过 adapter = new Adapter(create(type))

创建您的适配器

您还可以考虑删除字符串常量,例如 SharpLowKey 并用枚举替换它们。

但总的来说,看你的代码,我会问,在你的情况下使用适配器的目的是什么?我看不到你能从中得到什么