WhatDoIDo is a wrapper class that wraps an o object.
It defines the internal interface X , which has a y() method for creating an Object . This interface can be considered as a strategy for creating an object. When a WhatDoIDo object is created using new , the constructor is provided with an X object that will be used to create the object.
Creates a wrapped object and makes it available to client code using the z() method. This creates an object lazily. It uses the boolean b flag to track whether an object was created or not. When z() is called by the client to capture the wrapped object, if the flag is set, the object o returned. If the flag is not set, the object is created using the X strategy, which is provided when this WhatDoIDo object is WhatDoIDo . The link to the created object is saved and returned to the client. In addition, z() is synchronized since it creates an object if it has not already been created. If it has not been synchronized, two threads can eventually create an object each, and only one of them will be saved.
public class ObjectWrapper { private CreationStrategy strategy; private boolean objectCreated; private Object wrappedObject; public ObjectWrapper(CreationStrategy strategy) { this.strategy = strategy; } synchronized Object getWrappedObject() { if (!objectCreated) { wrappedObject = strategy.createObject(); objectCreated = true; } return wrappedObject; } public interface CreationStrategy { Object createObject(); } }
source share