Search code examples
javacommand-pattern

Using Command- Pattern to create an object and add this to an ArrayList


I have a Problem to understand the exercise. What I have to do is:

  1. Different users must be able to add and delete a ticket to a ticketsystem (in a List)
  2. I have to do this with the Command- Design- Pattern

But I actually don´t know how to do this. I have thought about the following:

Student press the "createTicketForinsideBuildingDamage"- Button

  • -> this sets the "executionCommand" to "insideBuildingDamageCommand" and executes it
  • -> this creates a "insideBuildingDamage"- class and it asks for the data like date, type, name...
  • -> !!!and this has to be added to the Ticketsystemlist automatically!!! but how can I do this?

Or am I completley wrong? I don´t want a solution like full code. But an idea, how I can do this. Thank you


Solution

  • Firstly, I think you should understand how the design pattern works and how the classes interact with each other. You can see an example here https://refactoring.guru/design-patterns/command.

    My way of doing it:

    Command.java

    // concrete commands will implement this interface
    // you can also use an abstract class if you want to have certain attributes, such as a TicketSystem
    public interface Command { 
        // this method can be set to return something useful instead of void, if needed
        void execute();
    }
    

    AddTicketCommand.java

    public class AddTicketCommand implements Command {
        // TicketSystem and Ticket attributes
    
        // constructor that initializes the attributes
    
        @Override
        public void execute() {
            // add the Ticket to the TicketSystem
        }
    }
    

    Invoker.java

    public class Invoker {
        private Command command;
    
        public void setCommand(Command command) {
            this.command = command;
        }
    
        public void invoke() {
            command.execute();
        }
    }
    

    Therefore, when you want to use a certain command, you set it with accordingly. For example: invoker.setCommand(new AddTicketCommand(new TicketSystem(), new Ticket())) and then call it with invoker.invoke().

    Hope it helped!