mardi 10 avril 2018

Using strategy design pattern with an abstract parameter

I am currently working on a pretty simple project to improve my SOLID and Design Patterns Knowledge. The idea was to create a "Smart Lock" for a door that can recognize a person by different parameters such as fingerprints, facial recognition, etc.

I immediately saw the potential in using the Strategy Design Pattern, and therefore I created a Lock interface and a Key abstract class:

public interface Lock {
    boolean unlock(Key key);
}

public abstract class Key {
    private String id;

    public String getId(){
        return (this.id);
    }
}

I created two classes that will extend Key - FacePhoto and FingerPrint:

public class FacePhoto extends Key {
}

public class FingerPrint extends Key {
}

Then I created classes that implement Lock such as FingerPrintRecognizer and FacialRecognizer:

public class FacialRecognizer implements Lock {
    @Override
    public boolean unlock(Key key) throws Exception {
        if(key instanceof FacePhoto){
            //check validity
            return true;
        }
        else {
            throw new Exception("This key does not fit this lock");
        }
    }
}

public class FingerPrintRecognizer implements Lock {
    @Override
    public boolean unlock(Key key) throws Exception {
        if(key instanceof FingerPrint){
            //check validity
            return true;
        }
        else {
            throw new Exception("This key does not fit this lock");
        }
    }
}

I couldn't really find a better way to handle cases in which users of the Lock interface will try to open Locks with keys that don't fit. Also, I had trouble with the "instanceof" if statement because it appears in every class that implements Lock.

Is Strategy a good practice in this case? if not, what would be a fine alternative?

Aucun commentaire:

Enregistrer un commentaire