设计实验
有 3 个开关:a
b c
有 3 个电灯:x y z
要求实现:
a 能控制 x
b 能控制 x, y
c 能 x
注意:1个灯泡可以被多个开关控制;1个开关可以同时控制多个灯泡
所谓“控制”:当开关操作时,当前灯泡的状态发生翻转。亮->灭 或 灭->亮
import java.util.*; class Light { private boolean state; // 灯的状态。true: 亮 public String toString() { if(state) return "亮"; else return "灭"; } // 翻转状态 public void change() { state = !state; } } class Switch { //Light[] a = ... Vector v = new Vector(); public void addLight(Light x) { v.add(x); } // 按了一下开关 public void press() { for(int i=0; i<v.size(); i++) { Light p = (Light)v.get(i); p.change(); // 反转电灯的当前状态 } } } public class MyTest { private static void show_light(Light x, Light y, Light z) { System.out.println(x + "," + y + "," + z); System.out.println("-----------------------"); } public static void main(String[] args) { Light x = new Light(); Light y = new Light(); Light z = new Light(); Switch a = new Switch(); Switch b = new Switch(); Switch c = new Switch(); a.addLight(x); b.addLight(x); b.addLight(y); c.addLight(x); show_light(x, y, z); a.press(); show_light(x, y, z); b.press(); show_light(x, y, z); c.press(); show_light(x, y, z); } }
03-04面向对象设计原则_设计实验
时间: 2024-10-10 14:04:29