Design Pattern Code Rewriting Practice
You are given "before" code that violates design pattern principles. Your task is to refactor it using
the using appropriate design pattern. Work in pairs or small groups, and be prepared to explain your
solution.
📋 The Problem: Complex Smart Home Setup
class Lights {
public void turnOn() { [Link]("Lights on"); }
public void turnOff() { [Link]("Lights off"); }
public void dim(int level) { [Link]("Dimming to " + level + "%"); }
public void setColor(String color) {
[Link]("Setting color to " + color);
}
}
class Thermostat {
public void setTemperature(int temp) {
[Link]("Setting temp to " + temp);
}
public void setMode(String mode) {
[Link]("Setting mode to " + mode);
}
public void turnOn() { [Link]("HVAC on"); }
public void turnOff() { [Link]("HVAC off"); }
}
class SecuritySystem {
public void arm() { [Link]("Security armed"); }
public void disarm() { [Link]("Security disarmed"); }
public void lockDoors() { [Link]("Doors locked"); }
public void unlockDoors() { [Link]("Doors unlocked"); }
}
class EntertainmentSystem {
public void turnOnTV() { [Link]("TV on"); }
public void turnOffTV() { [Link]("TV off"); }
public void setChannel(int channel) {
[Link]("Channel set to " + channel);
}
public void playMusic(String playlist) {
[Link]("Playing: " + playlist);
}
}
class Sprinklers {
public void startWatering() { [Link]("Sprinklers started"); }
public void stopWatering() { [Link]("Sprinklers stopped"); }
public void setSchedule(String time) {
[Link]("Schedule set to " + time);
}
}
public class SmartHome {
public static void main(String[] args) {
Lights lights = new Lights();
Thermostat thermostat = new Thermostat();
SecuritySystem security = new SecuritySystem();
EntertainmentSystem entertainment = new EntertainmentSystem();
Sprinklers sprinklers = new Sprinklers();
[Link]("\n=== Leaving Home ===");
[Link]();
[Link](18);
[Link]("eco");
[Link]();
[Link]();
[Link]("06:00");
[Link]("\n=== Coming Home ===");
[Link]();
[Link]();
[Link]();
[Link](50);
[Link](22);
}
}
public class HomeTheater {
public static void main(String[] args) {
Lights lights = new Lights();
Thermostat thermostat = new Thermostat();
EntertainmentSystem entertainment = new EntertainmentSystem();
[Link]("\n=== Watching TV ===");
[Link]();
[Link](20);
[Link]("comfort");
[Link]();
[Link](5);
[Link]("\n=== Not Watching TV ===");
[Link]();
[Link](50);
[Link]();
[Link](22);
}
}