In the Calss diagram at the link below, I want to implement the class diagram in java code using design pattern, one of them is to use abstract factory or factory method and Allow only one instance of any factory type you create ( singleton design pattern).

click the link to preview the class diagram

I have created the Concrete Stores using abstract factory, but when I try to implement the singleton, I have a problem since the singleton getinstance method is static, the code below shows the problem.

How to rewrite the IStoreFactory, and BookStoreFactory to call the singleton BookStore Class ?

public class BookStore extends Store {

 private volatile static BookStore uniqueInstance;
 static BookStoreFactory bookStoreFactory;

 private BookStore(BookStoreFactory bookStoreFactory) {
        this.bookStoreFactory = bookStoreFactory;
          }

    public static synchronized BookStore getInstance() {
        if (uniqueInstance == null) {
            synchronized (BookStore.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new BookStore(bookStoreFactory);
                }
            }
        }
        return uniqueInstance;
    }
}

public interface IStoreFactory {

 public   Store createStore();  

 }

public class BookStoreFactory implements IStoreFactory{

    private Store store;

       If(store == null){

     Store = bookStore.getInstance();
    }
     return store;
    }


    }

How Could I call bookstore.getInstance in the BookFactory Store = bookStore.getInstance();

0 Answers