nus-cs2030 / 2122-s2

CS2030 repository and wiki for AY 2021/2022 Sem 2
MIT License
0 stars 0 forks source link

Mock Q2c #592

Open GraceYongXM opened 2 years ago

GraceYongXM commented 2 years ago

Source

mock paper q2c traffic light q!

Description

anyone thought of a way to prevent cyclic dependencies?

part a implementation Red and Green depends on each other

was thinking of creating a new class NextLight which will determine which colour of light to return but its still cyclic since green -> next -> green/ amber/ red

Screenshots (if any):

Insert Images here if necessary

Swagston20 commented 2 years ago

Just create abstract class for each lights and then create anonymous class to toggle from one light to another

ReganKvioke commented 2 years ago

@Swagston20 Hey, do you mind sharing your code for this? I understand creating the abstract classes, but you lost me at the part to create an anonymous class to toggle. Like this toggle do I implement it in TrafficLight or in the various abstract classes? Thank you!

Swagston20 commented 2 years ago

Redlight redlight = new Redlight() { Redlight red = this;

@Override
toggle() {
    return new AmberLight() {
        @Override
        toggle() {
            return new GreenLight() {
                @Override
                toggle() {
                    return new AmberLight() {
                        @Override
                        toggle() {
                            return red;
                        }
                    }
                }
            }
        }
    }
}

}

ReganKvioke commented 2 years ago

@Swagston20 Thanks for the code, I saw it in another post that you sent, however where do you put this chunk of code into?

seantanyurong commented 2 years ago

If I'm not wrong, the generated redlight object should just be inserted as the first argument into the toggling method

joelleng commented 2 years ago

Hi, actually I am confused with this question and the concept of anonymous inner class. May I ask what is the purpose of defining a property i.e. in the new RedLight() {Redlight red = this; ...}