Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AY18/19 Q2 Cyclical Dependency #604

Open
muhdjabir opened this issue Apr 27, 2022 · 3 comments
Open

AY18/19 Q2 Cyclical Dependency #604

muhdjabir opened this issue Apr 27, 2022 · 3 comments

Comments

@muhdjabir
Copy link

Source

image

Description

Helloo, was doing this question and am stumped. I understand that the console start method relies heavily on logic and Logics invokes method also requires knowledge of the Consoles methods. How would you guys approach removing the cyclical dependency for this?

Screenshots (if any):

Insert Images here if necessary

@zannlimjm
Copy link

Following the Dependency inversion principle, declare an interface between both classes to break the dependency and invert the dependence from one? So maybe console class implements the new interface while logic's argument is the interface. Hope it helps!! a little hard to explain >.<

@muhdjabir
Copy link
Author

@zannlimjm OH! okay i get the gist of it will work on coding it out. Thanks alot1!!

@lukasleeyo
Copy link

lukasleeyo commented Apr 28, 2022

Hi there, I have tried it out after @zannlimjm mentioned the implementation. Can anyone help to see if this is correct? Thank you!

interface Logic { void invoke(String command); }

`class Console implements Logic {
private String id;

Console(String id) {
    this.id = id;
}

void feedback(String mesg) {
    System.out.println(id + ": " + mesg);
}

@Override
public void invoke(String command) {
    this.feedback(command + " executed");
}

void start() {
    Scanner sc = new Scanner(System.in);
    String command;
    do {
        System.out.print("Enter a command: ");
        command = sc.next();
        this.invoke(command);
    } while (!command.equals("exit"));
}

}`

class Main { public static void main(String[] args) { Console console = new Console("main"); console.start(); } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants