jeudi 25 février 2016

Java design pattern: Factory vs Singleton? in case of Multithread

It is advisable to create new object wisely and use the same Object instance instead of creating a new one. I am not very much confident in deciding the solution for creation of object in following scenario. There is a SOAP service class which has several method that is responsible for multiple customer. Please see below a template,

Public class SOAPService {          
            public Object getProductList(String CustId, String endPoint){
                SOAPStub stub = new SOAPStub(endPoint);
                Object productList = stub.getProductList();
                return productList;
            }
            public Object getProductInfo(String CustId, String productId, String endPoint){
                SOAPStub stub = new SOAPStub(endPoint);
                Object productInfo = stub.getProductList(productId);
                return productInfo;
            }
    }

Now I have introduce a factory method to create Object for each of the customer and put it in a map but i am confused when multiple thread of a single customer would access the service class. Wouldn't the behavior of object be like a singleton OR which might cause any deadlock issue OR make the thread to wait ?Please enlighten me on this.

    Public class SOAPService {
        private Map<String, SOAPStub> map = new HashMap<String, SOAPStub>();
        public SOAPStub getSOAPObject(String CustId, String endPoint){
            if(map.containsKey(CustId))
                return map.get(CustId);
            else{
                SOAPStub stub = new SOAPStub(endPoint);
                map.put(custId, stub);
                return stub;
                }
        }
        public Object getProductList(String CustId, String endPoint){
            SOAPStub stub = getSOAPObject(CustId, endPoint);
            Object productList = stub.getProductList();
            return productList;
        }

        public Object getProductInfo(String CustId, String productId, String endPoint){
            SOAPStub stub = getSOAPObject(CustId, endPoint);
            Object productInfo = stub.getProductList(productId);
            return productInfo;
        }
    }

Aucun commentaire:

Enregistrer un commentaire