Java-选择设计模式-2接口时使用相同的方法,除了其中一个有一个额外的参数
因此,我有两个接口(如下所示),一个用于常规/免费套件,另一个用于可购买套件。它们都包含2个方法,但在可购买工具包的“getIcon”方法中,我需要球员的个人资料作为参数,以便检查他们是否购买了工具包 链接这两个接口的最佳设计模式是什么?你能告诉我做这件事的代码吗 两个接口:Java-选择设计模式-2接口时使用相同的方法,除了其中一个有一个额外的参数,java,interface,Java,Interface,因此,我有两个接口(如下所示),一个用于常规/免费套件,另一个用于可购买套件。它们都包含2个方法,但在可购买工具包的“getIcon”方法中,我需要球员的个人资料作为参数,以便检查他们是否购买了工具包 链接这两个接口的最佳设计模式是什么?你能告诉我做这件事的代码吗 两个接口: public interface Kits { void giveKit(Player player); Item getIcon(); } public interface Purchasable
public interface Kits {
void giveKit(Player player);
Item getIcon();
}
public interface PurchasableKits {
void giveKit(Player player);
Item getIcon(Profile profile);
}
我试图使用适配器模式,但它似乎不正确,因为“getIcon”方法将配置文件作为参数,但没有使用它
public class KitAdapter implements PurchasableKits {
private Kits kits;
public KitAdapter(Kits kits) {
this.kits = kits;
}
@Override
public void givetKit(Player player){
kits.giveKit(player);
}
@Override
public void getIcon(Profile profile){
kits.getIcon();
}
}
提前感谢您有1个界面
可购买套件
。一个免费的工具包将实现该接口并调用getIcon(null)
红色标志是这两个接口几乎完全相同。并没有任何设计模式可以让您摆脱这种情况。这是一个棘手的问题,因为java避免了继承和循环继承的规则 我不认为您需要接口,您可以这样做:
public interface Kits {
void giveKit(Player player);
//a vargars usage
Item getIcon(Profile... p);
}
public class ConcreteClass implements Kits{
@Override
public void giveKit(Player player) {
// TODO Auto-generated method stub
}
@Override
public Item getIcon(Profile... o) {
//This is the ugly thing of this method. You must check the sent params.
//However I think it is better than send a null param, as the clean code suggest to avoid
if(o.length == 0)
System.out.println("without profile");
else
System.out.println("With profile");
return null;
}
}
public class Main {
public static void main(String[] args) {
ConcreteClass my = new ConcreteClass();
my.getIcon();
my.getIcon(new Profile());
}
}
输出:
无侧面
侧面
因此,我有两个接口(如下所示),一个用于常规/免费套件,另一个用于可购买套件。它们都包含2个方法,但在可购买工具包的“getIcon”方法中,我需要球员的个人资料作为参数,以便检查他们是否购买了工具包
在getIcon(…)
方法中是否需要配置文件是可购买的Kit
的实现细节。我只需要一个Kit
接口,该接口具有以下定义:
public interface Kit {
void giveKit(Player player);
Item getIcon(Profile profile);
}
因此,每次您想要获得图标时,您都会在配置文件中传递该图标,这取决于可购买的套件是否可以查看该配置文件。自由派只会忽略这个论点。有时传入null
,有时不传入意味着您事先知道它是否免费,这意味着您的模型有问题
关于您的代码的几个其他注释。只是我的意见:
- 具体类往往是名词。接口往往是动词。也许是
KitHandler
而不是Kit
- 类名往往是单数的,因此您可以将它们放在列表中。也许
Kit
(或KitHandler
)会更好,这样您就可以创建一个列表kits=…
- 我使用get方法返回字段,这意味着它们通常不接受参数。也许
getIcon
应该是generateIcon(…)
我不确定我是否理解这些接口的用途,但您至少可以通过使公共接口PurchableKits extends Kits
删除重复的giveKit()
方法。然后,该子接口将只有项getIcon(Profile Profile)
方法。或者忽略传递给它的任何Profile
。感谢您的响应!最初我确实有1个接口,但我认为我的设计很糟糕,因为我大部分时间都在传递null。但我想我只是开始想得太多了,因为我刚刚学习了设计模式,非常感谢反馈!我把代码改成了一个界面,还使用了你的名字建议,它们确实更有意义