The task of the team template; clarification needed; Java

Suppose you have a command:

public class PublishLastFiveCommand implements Command {
    private Producer p;

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

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

Additionally, the manufacturer allows you

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 Use:

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

Do I have an elegant way to protect against:

p.publishLastFive()

called directly?

+3
source share
3 answers

Ok guys, I get it.

Publication in the case, others may have the same issue.

Team:

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

On the server of the manufacturer

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 Result:

work:

publish5.execute();

work:

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

not working, optional

p.publishLastFive();
0
source

publishLastFive(), . (, PublishLastFiveCommand , , publishLastFive().

, new PublishLastFiveCommand(p).execute();. ?

+1

AFAIK is not at all, because execute () is publicly available.

0
source

Source: https://habr.com/ru/post/1788700/


All Articles