2

I am trying to figure out what this code does. It is based on a design pattern. Can someone explain what is going on, specially in the last method getNonTrivialStuff that is of type NonTrivialClass

public class E{
    private SomeOtherClass myObject = null;
    private String trivialString;

    public E(){
        trivialString = "Trivial";
    }

    public String getTrivialStuff(){
        return myTriv;
    }

    public NonTrivialClass getNonTrivialStuff(){
        if (myObject == null){
            myObject = SomeOtherClass.getObject();
        }  
            return myObject.getNonTrivialStuff();
    }

}
DoubleOseven
  • 271
  • 2
  • 13
  • What design pattern is it based on? – Willy du Preez Mar 14 '16 at 12:39
  • 1
    It looks like a poor mans implementation of a wrapper/proxy around a singleton. Basically the code uses lazy evaluation to setup a field in your class. So, there is really nothing special about it. The point is that initially the field `myObject` is null; and when getNonTrivialStuff is called the first time, that field is initialized and then used to return an instance of NonTrivialClass. So what exactly is it that you don't understand about it? – GhostCat Mar 14 '16 at 12:41
  • It is the 'someOtherClass' that confuses me. Shouldn't it be NonTrivialClass instead? – DoubleOseven Mar 14 '16 at 12:43

1 Answers1

2

It resembles Proxy_pattern.

If your class E implements an interface, which has been implemented by RealSubject as shown in below, E can be named as Proxy.

Proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes

UML diagram:

enter image description here

A proxy, in its most general form, is a class functioning as an interface to something else.

The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.

You can find more details about Proxy in below post:

What is the exact difference between Adapter and Proxy patterns?

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211