【问题标题】:Command pattern question; clarification needed; Java命令模式问题;需要澄清;爪哇
【发布时间】:2011-01-29 17:16:53
【问题描述】:

假设你有如下命令:

public class PublishLastFiveCommand implements Command {
    private Producer p;

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

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

另外生产者允许您

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

Command c;

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

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

问题:

预期用途是:

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

我有什么优雅的方法可以防止:

p.publishLastFive()

被直接调用?

【问题讨论】:

    标签: java command design-patterns


    【解决方案1】:

    如果您使publishLastFive() 方法受保护,则只有同一包中的对象可以访问该方法。 (假设你的 PublishLastFiveCommand 类在同一个包中,它可以毫无问题地调用该方法,但其他包中的客户端代码不能直接调用publishLastFive()

    我不明白你说阻止new PublishLastFiveCommand(p).execute(); 是什么意思。为什么要阻止这种情况?

    【讨论】:

      【解决方案2】:

      AFAIK 根本没有,因为 execute() 是公开的。

      【讨论】:

        【解决方案3】:

        好的,我明白了。

        发布以防万一,其他人可能有同样的问题。

        按指令:

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

        关于制片人

        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
        }
        

        广告结果:

        作品:

        publish5.execute();
        

        作品:

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

        不按要求工作

        p.publishLastFive();
        

        【讨论】: