mardi 16 avril 2019

How could I use an extended instance without modifying their code while using an enum version singleton pattern?

recently, when I ask how to make methods thread-safe in singleton pattern, someone told me that using an enum version singleton pattern is a good option. and by multiple threads. If the method has side effects (changes the state of some variable) then you need to think about protecting it (make it synchronized) or parts thereof. So I write code like this:

public enum ReStation {
    INSTANCE;  

    private List<Email> emailList;

    private ReStation() {
        emailList = new ArrayList<>();
    }

    public synchronized void recycleEmail(Email email) {
        System.out.println("Recycle station recycleing the email: "
                        + email.getContent());
        emailList.add(email);
    }

    public synchronized void deleteEmail(Email email) {
        emailList.remove(email);
    }

    public synchronized void clear() {
        emailList.clear();
    }
}

however, when I read the book named "Design Pattern-Elements of Reusable Object-Oriented Software", I come across such a paragraph as below :

  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

Given an enum can't be extended, I am really confused about How could I use an extended instance without modifying their code while using an enum version singleton pattern?

Aucun commentaire:

Enregistrer un commentaire