我是 headfirst 设计模式的读者,我注意到了这一点。
“好莱坞原则,不要叫我们,我们叫你”
这意味着高级组件告诉低级组件“不要打电话给我们,我们打电话给你”
高级组件是一个具有与其他低级组件一起定义的行为的类。
我的问题是……这个例子是否违反了不叫我们,我们叫你的原则?这也来自使用状态模式的书。
public class GumballMachine
{
//other state instance here
State NoQuarterState;
State HasQuarterState;
public GumballMachine(int numberGumballs)
{
NoQuarterState = new NoQuarterState(this);
HasQuarterState = new HasQuarterState(this);
//other state objects here assigning to state instance
}
public void insertQuarter()
{
state.insertQuarter();
}
void setState(State state)
{
this.state = state;
}
public State getHasQuarterState()
{
return hasQuarterState;
}
//more code here
}
==================================================== ===================
public interface State
{
//abstract methods
}
==================================================== ===================
public class NoQuarterState implements State
{
GumballMachine gumballMachine;
public NoQuarterState(GumballMachine gumballMachine)
{
this.gumballMachine = gumballMachine;
}
public void insertQuarter()
{
System.out.println("You inserted a quarter");
gumballMachine.setState(gumballMachine.getHasQuarterState()); // change the state to HasQuarterState
}
}
因为在这个例子中GumballMachine需要NoQuarterState的insertQuarterBehavior()来作为它自己的insertQuarterBehavior,所以这意味着GumballMachine类是高级组件,而NoquarterState类是低级组件。但是看看NoQuarterState类,该类还依赖于gumballMachine 的 setState()和getHasQuarterState()的insertQuarter() 行为。
他们相互依赖。通函 - 依赖关系