CMPUT 301

Software Engineering

Practice w23hm3q3


Midterm 3 Question 3 (March 29) -- Hindle

Submit a PDF, PNG or JPEG

5 marks

You must add your CCID to your answer

Dependency Injection with Singleton Pattern (UML class diagram)

This code represents the attempt to test a networked toaster. But we’re having a hard time testing it because we used the singleton pattern. Combine dependency injection with the singleton pattern so we can inject a mock object as the singleton. Provide a UML class diagram depicting the structure and operations one would expect after refactoring this code to allow dependency injection on the singleton. You cannot modify ToastCommand, or MockToaster. Modify the singleton with dependency injection.

You must provide the 1 line of Java code that we need to add in ToastCommandTest.testOnFire in a UML comment (see example below).

Image

Draw the resulting UML class diagram of the refactored code, including the . Provide the basic abstractions, attributes, methods, relationships, multiplicities, and navigabilities as appropriate. "...” or “//” means much code is omitted.

class Toaster {
    /* We have control over this class /
    private static Toaster instance = new Toaster();
    protected Toaster() { / ... / }
    public static Toaster getInstance() {
        return instance;
    }
    // tells us if the toaster is on fire.
    public boolean onFire() { / ... / }
    / ... /
}
class ToastCommand {
    // do not modify this class
    void toast() {
        Toaster p = Toaster.getInstance();
        if (p.onFire()) { // test the code inside this if block
            throw new ToasterOnFireException("Toaster Meltdown");
        }
        / ... /
    }
}
class MockToaster extends Toaster {
    // do not modify this class
    MockToaster() { / ... / }
    public boolean onFire() { return true; }
    / ... */
}
class ToastCommandTest {
    // modify 1 line of this class
    void testOnFire() {
        ToastCommand t = new ToastCommand();
        MockToaster mock = new MockToaster();
                                           // fill in this line
        try {
            t.toast();
            assert( false ); // shouldn't reach here
        } catch (ToasterOnFireException e) {
            assert( true );
        }
    }
}