jeudi 10 janvier 2019

Implement Factory Pattern

Currently I'm busy with implement the Factory Pattern into my Java Code. I've got these classes:

CipherStorage

public class CipherStorage {

    protected String transformation;
    protected String provider;
    protected String providerPair;

    public CipherStorage(String transformation, String provider, String providerPair){
        this.transformation = transformation;
        this.provider = provider;
        this.providerPair = providerPair;
    }
}

CipherStorageProcessor (Interface)

public interface CipherStorageProcessor {
    byte[] encryptData(String keyName, String input, @Nullable SharedPreferences pref);
    byte[] decryptData(String keyName, byte[] encrypted, @Nullable SharedPreferences pref);
}

CipherStorageRSA

public class CipherStorageRSA extends CipherStorage implements CipherStorageProcessor {

    public CipherStorageRSA(String transformation, String provider,String providerPair){
        super(transformation, provider, providerPair);
    }
}

CipherStorageAES

public class CipherStorageAES extends CipherStorage implements CipherStorageProcessor {

    public CipherStorageAES(String transformation, String provider, String providerPair){
        super(transformation, provider, providerPair);
    }
}

CipherStorageFactory

public class CipherStorageFactory {

    public CipherStorage getCipher(String cipherType) {
        if (cipherType == null) {
            return null;
        }
        if (cipherType.equalsIgnoreCase("AES")) {
            return new CipherStorageAES();

        } else if (cipherType.equalsIgnoreCase("RSA")) {
            return new CipherStorageRSA();

        }
    }
}

Is this code made any sense? Is it correct to add parameters into the factory? Is there an better way to this?

Already thanks for any help.

PS: i removed the two interface functions from the classes to prevent a lot of code.

EDIT:

When i create an instance of RSA for example:

CipherStorage RSA = CipherStorageFactory.getCipher("RSA");

I've got no access to the methods into the interface?

Aucun commentaire:

Enregistrer un commentaire