我对设计模式相对较新,在下面的例子中,我使用的是我认为的策略模式。但是,我在一些,而不是全部,具体策略中重复自己,并想知道有没有办法避免这种情况?注意ACommand和CCommand在做一些独特的事情之前是如何拥有相同的代码的。
public interface Command
{
public boolean execute(CommandSender sender, String[] args);
public String getName();
//...
}
public abstract class PlayerCommand implements Command
{
protected BukkitPlugin plugin = BukkitPlugin.getInstance();
private String name;
//...
public PlayerCommand(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
//...
}
ACommand
public class ACommand extends PlayerCommand
{
public ACommand()
{
super("A");
}
public boolean execute(CommandSender sender, String[] args)
{
Player player = (Player) sender;
PlayerInventory inventory = player.getInventory();
ItemStack itemInHand = inventory.getItemInHand();
if(itemInHand.getType() != Material.COMPASS)
{
sender.sendMessage("You must be holding a phone to use this command");
return true;
}
int id = itemInHand.getDurability();
MobilePhoneManager phoneManager = plugin.getMobilePhoneManager();
boolean isMobilePhone = phoneManager.isMobilePhone(id);
if(!isMobilePhone)
{
sender.sendMessage("You must be holding a mobile phone to use this command");
return true;
}
//DO SOMETHING UNIQUE HERE
}
}
BCommand
public class BCommand extends PlayerCommand
{
public BCommand()
{
super("B");
}
public boolean execute(CommandSender sender, String[] args)
{
//SOMETHING ELSE
}
}
的CCommand
public class CCommand extends PlayerCommand
{
public CCommand()
{
super("C");
}
public boolean execute(CommandSender sender, String[] args)
{
Player player = (Player) sender;
PlayerInventory inventory = player.getInventory();
ItemStack itemInHand = inventory.getItemInHand();
if(itemInHand.getType() != Material.COMPASS)
{
sender.sendMessage("You must be holding a phone to use this command");
return true;
}
int id = itemInHand.getDurability();
MobilePhoneManager phoneManager = plugin.getMobilePhoneManager();
boolean isMobilePhone = phoneManager.isMobilePhone(id);
if(!isMobilePhone)
{
sender.sendMessage("You must be holding a mobile phone to use this command");
return true;
}
//DO SOMETHING UNIQUE HERE
}
}
答案 0 :(得分:7)
您可以使用template pattern作为ACommand
和CCommand
之间的公共基类的基础。基类中的模板方法将保存公共代码,然后调用(abstract
)方法到doSomethingUnique()
。
答案 1 :(得分:0)
bool canExecute();
boll canExecute(args)
您通常看不到execute方法返回任何内容。
HTH,
Berryl