2011-01-29 48 views
3

假設你有一個命令如下:命令模式問題;需要澄清; Java的

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() 

直接叫什麼名字?

回答

0

好球員,我得到它

出版的情況下,其他人可能有同樣的問題

在命令:。

@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(); 
0

AFAIK根本沒有,因爲execute()是公共的。

1

如果您使publishLastFive()方法受保護,則只有同一包中的對象才能訪問該方法。 (假設你的PublishLastFiveCommand類是在同一個包,它可以調用該方法沒有問題,但在其他包的客戶端代碼不能直接調用publishLastFive()

我不明白你的意思防止new PublishLastFiveCommand(p).execute();。爲什麼要防止這種