padlock-solver/src/main/java/com/cleverthis/interview/PadlockJavaAdapter.java

50 lines
1.9 KiB
Java

package com.cleverthis.interview;
import com.cleverthis.interview.padlock.PadlockImpl;
/**
* The concrete implementation of PadlockAdapter that communicates with the padlock directly through a Java
* class. This implementation also contains a cache that it keeps in sync with the underlying API, as a front-line
* optimization against unnecessary write operations.
*/
public class PadlockJavaAdapter extends PadlockImpl implements PadlockAdapter {
/**
* Intermediate cache between the underlying padlock API and any code that interfaces with the PadlockAdapter
* API.
*/
private final Integer[] inputBufferState;
/**
* Create a padlock instance.
*
* @param numpadSize The number of buttons on the numpad of this lock.
*/
public PadlockJavaAdapter(int numpadSize) {
super(numpadSize);
inputBufferState = new Integer[numpadSize];
for(int i = 0; i < this.getNumpadSize(); i++) {
inputBufferState[i] = i;
super.writeInputBuffer(i, i);
}
}
/**
* Writes to the underlying input buffer, but only if the cache shows that the write is necessary
* @param address The position / index of the button that is pressed. For example, address 0 is the first button pressed.
* @param keyIndex The value of the button that is pressed. Cannot be greater than the numpad size, as the buttons increment
* sequentially
* @return The old value that was replaced, which is the same as keyIndex if a write operation doesn't actually occur.
*/
@Override
public Integer writeInputBuffer(int address, int keyIndex) {
if(inputBufferState[address] != keyIndex) {
inputBufferState[address] = keyIndex;
return super.writeInputBuffer(address, keyIndex);
} else {
return keyIndex;
}
}
}