我对设计模式比较陌生,在下面的示例中,我使用了我认为是策略模式的东西。但是,我在一些(不是全部)具体策略中重复自己,想知道有没有办法避免这种情况?注意 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;
}
//...
}
指令
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
}
}
B命令
public class BCommand extends PlayerCommand
{
public BCommand()
{
super("B");
}
public boolean execute(CommandSender sender, String[] args)
{
//SOMETHING ELSE
}
}
C命令
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
}
}