0

In both code single instance is used but I'm just wondering which approach is better

For e.g.:

An Interface

  interface A{

        void someOperation();

    }

Implementation of that interface

class AImpl implements A{
    private Object A;       

    public AImpl(Object A){
       this.A = A;
    }

   void someOpearion(){
   //

   ......
   //
    }

}

Factory interface

interface Factory{
    A getA();
}

Factory Implementation

class FactoryImpl implement Factory{
    A a;
    A getA(){
    if(a == null){
        a=new AImpl();
    }
    return a;
    }
}

Now There are two approaches with just 1 basic difference to use this Factory

Approach 1:

class View{

    View(){
       someMethod();
    }

    void someMethod(){
        factory.getA().someOperation();
    }
 }

Approach 2:

class View{
    A a;
    View(){
       this.a = factory.getA();
       someMethod();
    }

    void someMethod(){
        a.someOperation();
    }
 }

In approach 1 for every operation I need to access view using factory while in approach 2 I'm using factory instance locally.

I think approach 2 is better because its not using method Channing or interface callback.Am I right Can some one explain elaborate this .

2 Answers 2

1

Approach 2 can be marginally faster if you call someMethod() several times, since you save one method call. However, in real life this will not affect the runtime of your application, unless you make millions of calls.

I personally would chose between the two approaches based on maintainability and code simplicity. If you make the same call in several places within one class, I would use approach2. Otherwise approach 1 is simpler and easier to understand.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree with you there is just 1 issue with 2nd approach in 2nd approach we are using single reference but also using memory 2 times. so in limited memory we may face issue.
0

As Thomas explained I too believe it depends on the situation, as almost all computer science approaches behave.

As your factory object creation in not thread safe, there is a higher probability to get multiple objects created of A in 1st approach in a multi-threaded environment. (2nd approach is not immune as well).

On the other hand 2nd approach adheres to the "Has-A" relationship in OOP, might come in handy when modeling your system.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.