Java – which pattern of using policy patterns can avoid duplicate code in concrete policies?
•
Java
I am unfamiliar with design patterns. In the following example, I use what I think is the strategy pattern However, I repeat myself in some, not all, specific strategies, and wonder if there is any way to avoid this situation? Notice how acommand and ccommand have the same code before doing something unique
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 of
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 } }
Solution
You can use template pattern as the basis for the common base class between acommand and ccommand The template method in the base class will save the common code and then call (Abstract) to execute doSomethingUnique ().
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码