Encapsulating Object Creation in Java

Encapsulating Object Creation Polymorphism enables code to be more abstract. When your code references an interface instead of a class, it loses its coupling to that class and becomes more flexible in the face of future modifications. This use of abstraction was central to many of the techniques of the previous chapters. Class constructors are the one place where such abstraction is not possible. If you want to create an object, you need to call a constructor; and calling a constructor is not possible without knowing the name of the class. This chapter addresses that problem by examining the techniques of object caching and factories. These techniques help the designer limit constructor usage to a relatively small, well-known set of classes, in order to minimize their potential liability.

Object Caching

Suppose you want to write a program that analyzes the status of a large number of motion-detecting sensors, whose values are either “on” or “off.” As part of that program, you write a class Sensors that stores the sensor information in a list and provides methods to get and set individual sensor values.

public class Sensors

{

private List L = new ArrayList<>();

public Sensors(int size)

{

for (int i=0; i<size;i++)

{

L.add(new Boolean(false));

}

public boolean getSensor(int n)

{

Boolean val = L.get(n);

return val.booleanValue();

}

public void setSensor(int n, boolean b)

{

L.set(n, new Boolean(b));

}

}

This code creates a lot of Boolean objects: the constructor creates one object per sensor and the setSensor method creates another object each time it is called. However, it is possible to create far fewer objects. Boolean objects are immutable (that is, their state cannot be changed), which means that Boolean objects having the same value are indistinguishable from each other. Consequently, the class only needs to use two Boolean objects: one for true and one for false. These two objects can be shared throughout the list.

For More on content, visit https://www.itguidekolkata.in/2021/05/encapsulating-object-creation-in-java.html

--

--