这些是我的.java类。我是否正确地实现了适配器模式?
接口播放
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类,它创建一个Guitar.java对象并调用它的方法();
发布于 2015-10-06 11:58:10
我有几个建议:
移动此代码:
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))创建适配器了。
您还可以考虑删除字符串常量,如Sharp或LowKey,并将它们替换为枚举。
但是总的来说,看看您的代码,它给我带来了一个问题:在您的情况下使用适配器的目的是什么?我看不出你能从中得到什么
https://stackoverflow.com/questions/32968612
复制相似问题