Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- // test class
- public class QA8310825 {
- public static void main(String[] args) {
- LightSystem system =
- new LightSystem(new Swich("f1"), new Swich("f2"), new Swich("f3"));
- system.showState();
- system.turnSwich1(); system.showState();
- system.turnSwich1(); system.showState();
- system.turnSwich2(); system.showState();
- system.turnSwich3(); system.showState();
- system.turnSwich2(); system.showState();
- system.turnSwich1(); system.showState();
- }
- }
- class Swich {
- private enum State {
- Left, Right
- }
- private String floor;
- private State state;
- public Swich(String floor) {
- this.floor = floor;
- this.state = State.Left;
- }
- public String getFloor() {
- return this.floor;
- }
- public State getState() {
- return this.state;
- }
- public void toggle() {
- if (this.state == State.Left) {
- this.state = State.Right;
- return;
- }
- this.state = State.Left;
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("<Floor:" + this.getFloor());
- sb.append(", " + this.getState().name());
- sb.append(">");
- return sb.toString();
- }
- }
- class LightSystem {
- private enum Light {
- On, Off
- }
- private Map<Integer, Swich> swiches = new TreeMap<Integer, Swich>();
- private Light lamp;
- public LightSystem(Swich... s) {
- for (int i = 0; i < s.length; i++) {
- int size = this.swiches.size(); // auto increment
- this.swiches.put(size, s[i]);
- }
- this.lamp = Light.Off;
- }
- public Light getLight() {
- return this.lamp;
- }
- public void showState() {
- System.out.println(this);
- }
- public void turn() {
- if (this.lamp == Light.Off) {
- this.lamp = Light.On;
- return;
- }
- this.lamp = Light.Off;
- }
- private Swich find(String name) {
- Swich ret = null;
- for (Swich s : this.swiches.values()) {
- if (s.getFloor().equals(name)) {
- ret = s;
- break;
- }
- }
- return ret;
- }
- private boolean turnSwich(Swich swich) {
- Swich s = this.find(swich.getFloor());
- if (s == null) { return false; }
- s.toggle();
- this.turn();
- return true;
- }
- public void turnSwich1() {
- this.turnSwich(this.swiches.get(0)); // 0 means first inserts
- }
- public void turnSwich2() {
- this.turnSwich(this.swiches.get(1));
- }
- public void turnSwich3() {
- this.turnSwich(this.swiches.get(2));
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("Lamp: " + this.getLight().name() + ", swiches: ");
- sb.append(this.swiches.values());
- return sb.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement