mercredi 30 novembre 2022

Facade class implementation of 2 classes with almost same methods

I've you classes defined in different path with the same name defining almost same methods. I'm basically looking for a clean way to implement a Facade class for this scenario so that I don't have to apply switch statement to define the class. For instance I've these 2 interface defined

This is defined in xyz/V1/* public interface A {

    public abstract getService();

    public abstract void getVersion();
}

This is defined in xyz/V2/* public interface A {

    public abstract getService();

    public abstract void getVersion();

    public abstract void newMethodforV2();
}

Code I've implemented right now.

Constructor() {
    try {
        xyz.V2.A service = xyz.V2.A.getService();
        VERSION = 2;
    } catch (NoSuchElementException e) {
        try {
            xyz.V1.A service = xyz.V1.A.getService();
            VERSION = 1;
        } catch (NoSuchElementException f) {
                
        }
}
// For all function I've to do something similar
void doSomething() {
    switch (VERSION) {
        case 1:
            return V1.A.getService().doSomething()
        case 2:
            return V2.A.getService().doSomething()
        }
}

This is what something I'm looking to make it clean.

private A service;
Constructor() {
    try {
        service = xyz.V2.A.getService();
    } catch (NoSuchElementException e) {
        try {
            service = xyz.V1.A.getService();
        } catch (NoSuchElementException f) {
                
        }
}
// I want to implement something like this.
void doSomething() {
    service.doSomething();
}

I cannot modify classes/interface "A" here. Also is there a way I can define a class to do something like this

try {
    service = xyz.V2.A.getService();
} catch (NoSuchElementException e) {
     service = new V1toV2Facade(xyz.V1.A.getService());

Aucun commentaire:

Enregistrer un commentaire