dimanche 31 mai 2020

Implement strategy pattern with enum

I'm trying to create a service to handle different payment methods. I want to implement strategy pattern. I'd like to have an enum with the different payment methods. This is an example of what I have:

public enum Pay {
    CREDITCARD(1) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }

    },
    OTHERMETHOD(2) {
        @Override
        public void pay() {
            System.out.println("Payment functionality");
        }
    };

    private int id;

    Payment(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public abstract void pay();
}

somewhere in the client:

user.setPay(Pay.CREDITCARD);
user.pay();

The problem with this approach is that method "pay" could be have a lot of logic so I'd like to have it in a different class. I could define an interface like this:

public interface Pay {
    void pay();
}

public class CreditCard implements Pay {
    @Override
    public void pay() {
    }
}

public class OtherMethod implements Pay {
    @Override
    public void pay() {
    }
}

somewhere in the client:

if (method.equals("creditcard")) {
    user.setPay(new CreditCard());
    user.pay();
}
else {
    user.setPay(new OtherMethod());
    user.pay();
}

but I like much more how it looks with Enum and that the reason to keep that way. Thanks

Aucun commentaire:

Enregistrer un commentaire