public class Elevator () { Button firstFloorbutton = ButtonFactory.getButtonInstance(this, 1); 按钮 secondFloorbutton = ButtonFactory.getButtonInstance(this, 2); 按钮第三层按钮 = ButtonFactory.getButtonInstance(this, 3); 按钮fourthFloorbutton = ButtonFactory.getButtonInstance(this, 4);
Fan fan1 = FanFactory.getFanInstance(this);
Light light1 = LightFactory.getInstance(this);
private void goUp()
{
.....
}
private void goDown()
{
......
}
.............
}
============================
public class Button()
{
Elevator E;
int floor;
public button (Elevator E, int floor )
{
this.E = E;
this.floor = floor;
}
public void buttonPressed()
{
//logic to determine which floor the elevator is currently at and determine whether to go up or down to reach "this.floor"
E.goUp(); // if need to go up
else
E.goDown() // if need to go down
}
}
==========================
public class ButtonFactory()
{
public Button getButtonInstance(Elevator E, int floor)
{
Button b =new Button(E, floor);
return b;
}
}
==================
public class FanFactory(){ .................}
=====================
public class LightFactory() { ........... }
==========================
Elevator 和 Button 类之间存在什么样的关系?
根据Kathy and Bert (SCJP)第 92 页:HAS-A 关系基于使用而不是继承。换句话说,如果 A 类中的代码引用了 B 类的一个实例,那么 A 类就具有 B 类。
在我的示例 Elevator 类代码中引用了 Button 的实例,而 Button 引用了 Elevator 类的实例。
任何人都可以澄清这一点。