Search code examples
javamethodscomposition

How to secure methods of composition?


I have PC class and Monitor class. How to secure method of class monitor that you could not use it when the PC is switched off (status)?

public class Pc {
private Case theCase;
private Monitor theMonitor;
private Motherboard theMotherboard;
private boolean status;

public void turnOn(){
    System.out.println("Pc turned on!");
    status = true;
}
public void turnOff(){
    System.out.println("Pc turned off!");
    status = false;
}

and inside Monitor class

public void drawPixelArt(int heigh, int width, String color){
    System.out.println("Drawing pixel at " + heigh + " x "+ width + " px.");
}

So when (status == false) I do not want to be able to call any method.

e.g thePc.getTheMonitor().drawPixelArt(1200, 1000, "RED");

getTheMonitor() returns Object, so I can't try catch it.

Can someone help me how to deal with it?


Solution

  • I think you have properly designed the PC object as an aggregate of its parts, using the composition relationship between them. However, the weak point here is to give access to the actual components, since it makes possible to violate the invariants you have placed yourself (for example, you cannot draw in the Monitor unless the PC is turned on, which makes perfect sense).

    Maybe you would like to hide the details of the components and offer a unified interface to every operation through the PC object, implementing in some way a Facade pattern (https://en.wikipedia.org/wiki/Facade_pattern)