3

Suppose you have a command as follows:

public class PublishLastFiveCommand implements Command {
    private Producer p;

    public PublishLastFiveCommand(Producer p) {
    this.p = p;
    }

    public void execute() {\    
    p.publishLastFive();
    }
}

Additionally producer allows you to

public void publishLastFive() {
    System.out.println("publishing last 5");
}

Command c;

public void setCommand(Command c) {
    this.c = c;
}

public void execute() {
    c.execute();
}

Question:

Intended usage is:

Command publish5 = new PublishLastFiveCommand(p);
p.setCommand(publish5);
p.execute();

Is there a graceful way for me to protect against:

p.publishLastFive()

being called directly?

3 Answers 3

1

If you make the publishLastFive() method protected, only objects in the same package can access that method. (Assuming that your PublishLastFiveCommand class is in the same package, it can invoke that method without a problem, but client code in other packages cannot directly invoke publishLastFive().

I don't understand what you mean about preventing new PublishLastFiveCommand(p).execute();. Why do you want to prevent this?

Sign up to request clarification or add additional context in comments.

Comments

0

AFAIK not at all, because execute() is public.

Comments

0

Ok guys, i got it.

Publishing in case, others may have the same question.

On command:

@Override
public void execute() {
    p.setCommand(this);      <-- add this line
    p.publishLastFive();
}

On producer

public void publishLastFive() {
    if (c != null) {         <--- add null check
        System.out.println("publishing last 5");
    } 
}

Command c = null;

public void setCommand(Command c) {
    this.c = c;
}

public void execute() {
    c.execute();
    c = null;                <-- once done executing, set command to null
}

Ad a result:

works:

publish5.execute();

works:

p.setCommand(publish5);
p.execute();

does not work, as desired

p.publishLastFive();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.