The topic of this chapter is to create and destroy objects: When to create and how to create objects, when to avoid creation, how to avoid creation, how to ensure that objects are destroyed in a timely manner, and how to manage the cleanup actions before object destruction. To allow a class to obtain its instance, a common method is to provide a public constructor. Another method should also have a place in each programmer's tool set: the class can provide a public static factory method, which returns an instance of the class. [Example] The following is a simple example in the code of the Boolean class (the packaging class corresponding to the basic type boolean). This method converts a boolean simple type into a Boolean object reference. [Java] public static Boolean valueOf (boolean B) {return B? Boolean. TRUE: Boolean. FALSE;} note that the static factory method mentioned here is different from the factory method mode in the design mode. It does not have direct equivalents in the design mode. Class can be provided to its customer static factory method, used to replace the constructor method, or as a supplement to the constructor method. Replacing the public constructor with the static factory method has both advantages and disadvantages. Advantage 1: static factory methods are different from constructors and they have names. If the parameters of the constructor cannot accurately describe the objects being returned, the static factory method with the proper name is easier to use and the corresponding client code page is easier to read. [Example] For example, the constructor BigInteger (int, int, Random) returns a BigInteger that may be a prime number, and it is better to use a static factory method named BigInteger. probablePrime. (JDK1.4 adds this method .) [Java] public class BigInteger extends Number implements Comparable <BigInteger> {public static BigInteger probablePrime (int bitLength, Random rnd) {if (bitLength <2) throw new ArithmeticException ("bitLength <2"); // The cutoff of 95 was chosen empirically for best performance return (bitLength <SMALL_PRIME_THRESHOLD? SmallPrime (bitLength, substring, rnd): largePrime (bitLength, DEFAULT_PRIME_CERTAINTY, rnd);} public BigInteger (int bitLength, int certainty, Random rnd) {BigInteger prime; if (bitLength <2) throw new ArithmeticException ("bitLength <2"); // The cutoff of 95 was chosen empirically for best performance prime = (bitLength <95? SmallPrime (bitLength, certainty, rnd): largePrime (bitLength, certainty, rnd); signum = 1; mag = prime. mag ;}} a class can have only one corresponding constructor for the specified method signature. Programmers usually avoid this restriction by providing two constructor functions. Their parameter list is just that the order of parameter types is different. This is really a bad idea. API users will not remember which constructor is and often call the wrong constructor unintentionally. When others read the code that uses the constructor, they will not know what the code is, unless you refer to the Class documentation. The static factory method has a name, so there is no such restriction. If a class requires multiple constructors with the same method signature, the static factory method is used to replace the constructor, and the method name is carefully selected to highlight the differences between them. Advantage 2: The static factory method is different from the constructor, and you do not need to create a new object each time you call it. This allows the non-variable class (Item15) to use a pre-created instance, or cache the instance when it is created, and then distribute it to the customer to avoid unnecessary duplicate objects. The Boolean. valueOf (boolean) method demonstrates this technology: It never creates objects. This technology is similar to the Flyweight mode. If the client often requests to create the same object, this technology can greatly improve the performance, especially when the object creation overhead is large. The static factory method can return the same object in the case of another counterpoint, which allows the class to strictly control which instances exist at which time. This type is also known as the instance-controlled class ). There are several reasons for writing an instance-controlled class: first, the instance-controlled allows a class to be single-instance (Item3) or non-instantiated (Item4); at the same time, the instance control allows the non-variable class (Item15) to ensure that there are no two equal instances, that is, only when a = B has. equals (B). If a class makes this guarantee, its client can use the = Operator to strip the equals (Object) method, which may improve the performance. The enumeration type (Item30) ensures this. Advantage 3: The static factory method is different from the constructor. It can return any sub-type objects. This gives you great flexibility when selecting the type of the returned object. One application with this flexibility is that the API can return an object without making the object class public. Hiding implementation classes in this way can produce a very compact API. This technique is applicable to interface-based frameworks (Item18) in which interfaces become natural return types for static factory methods. Because the interface cannot have static methods, according to the Convention, the static factory method of interface Type is put in a non-instantiable class (Item4) named Types. [Example] For example, the Java Collection framework has 32 set interfaces for convenient implementation, and provides unchangeable sets and synchronization sets. Almost all implementations are exported through a static factory method in a non-instantiated class (java. util. Collections), and the classes of returned objects are non-public. -- The return type of the Collections. unmodifiableMap (Map) method is UnmodifiableMap, which is a private class! [Java] public class Collections {public static <K, V> Map <K, V> unmodifiableMap (Map <? Extends K ,? Extends V> m) {return new UnmodifiableMap <K, V> (m);} private static class UnmodifiableMap <K, V> implements Map <K, V>, serializable {} If you export all the preceding convenient implementations as public classes, the set framework API will be bloated. In addition, this is not only the decrease in the number of APIS, but also the reduction of conceptual weight. Users know that the returned objects are precisely defined by the API through the interface, so they do not need to read additional class documents for the Implementation class. In addition, the static factory method requires the client to reference the returned object through the interface, instead of referencing the returned object through the implementation class. This is usually a good habit. The object type returned by the public static factory method can not only be non-public, but also return different types based on different parameters. Any subtype of the declared return type is allowed. To improve Software maintainability and performance, the return type may vary with versions. [Example] the java. util. EnumSet class introduced in JDK does not have a public constructor and only has a static factory method. Based on the size of the underlying Enumeration type, these factory methods can return two implementations: if there are 64 or fewer elements (most enumeration types are like this), the static factory method returns a RegularEnumSet instance, A single long is supported. If the enumeration type has 65 or more elements, the static factory method returns the JumboEnumSet instance, which is supported by the long array. The existence of these two implementation classes is invisible to the client. If RegularEnumSet provides performance advantages for small enumeration types, it can be deleted in later versions without side effects. Similarly, if the performance can be improved, the third or fourth implementation of EnumSet can be added in later versions. The client does not know or care about the type of the object returned by the static factory. The client only cares that it is a subclass of EnumSet. [Java] public abstract class EnumSet <E extends Enum <E> extends actset <E> implements Cloneable, java. io. serializable {public static <E extends Enum <E> EnumSet <E> noneOf (Class <E> elementType) {Enum [] universe = getUniverse (elementType ); if (universe = null) throw new ClassCastException (elementType + "not an enum"); if (universe. length <= 64) return new RegularEnumSet <E> (elementType, unive Rse); else return new JumboEnumSet <E> (elementType, universe );}} class RegularEnumSet <E extends Enum <E> extends EnumSet <E >{} class JumboEnumSet <E extends Enum <E> extends EnumSet <E> {}, the class to which the returned object belongs may not even exist. The flexibility of the static factory method forms the foundation of the service provider framework (service provider frameworks), such as Java database connection API (JDBC ). The so-called service provider framework is a system in which multiple service providers implement a service. The system makes these implementations available to the client and decouples them from the implementation. There are three important components in the service provider framework: service interface, which is responsible for providing implementation; provider registration API, which is used by the system to register and implement, allows the client to access the service. The client uses the service access API to obtain an instance of the service. It generally allows the client to specify the conditions for selecting the provider, but is not mandatory. If this parameter is not specified, the API returns a default instance. Service access API is a "flexible static factory" that forms the basis of the service provider framework. The service provider framework also has the fourth optional component: service provider interface, which is used by the provider to create its service implementation instance. If there is no service provider interface, the implementation is registered through the class name and instantiated through reflection (Item53 ). [Example] Taking JDBC as an example, Connection is a service interface and DriverManager. registerDriver is the provider registration API (provider registration API); DriverManager. getConnection is a service access API, and Driver is a service provider interface ). The service provider framework has multiple variants. For example, a service access API can return more abundant service interfaces than the provider requires through the adapter mode. [Example] The following is a simple example with a Service provider interface and a default provider: [java] // Service provider framework sketch // -- 1) service interface public interface Service {// service-specific methods go here} // -- 4) Service provider interface public interface Provider {Service newService ();} // Noninstantiable class for service registration and access public class Services {private Services () {}// pervents instantiation // maps service names to s Ervices private static final Map <String, Provider> providers = new ConcurrentHashMap <String, Provider> (); public static final String DEFAULT_PROVIDER_NAME = "<def>"; // -- 2) provider registration API public static void registerdefaprovider (Provider p) {registerProvider (DEFAULT_PROVIDER_NAME, p);} public static void registerProvider (String name, Provider p) {providers. put (name, p);} // -- 3) servic E access API: static factory method public static Service newInstance () {return newInstance (DEFAULT_PROVIDER_NAME);} public static Service newInstance (String name) {Provider p = providers. get (name); if (p = null) {throw new IllegalArgumentException ();} return p. newService () ;}} advantage 4: The static factory method is more concise when creating parameterized instances. If you call the constructor of the parameterized class, you must specify the type parameter, even if the type parameter is specified in the context. This usually requires you to provide the type parameter for two consecutive times: [java] <span style = "color: #333333;"> Map <String, list <String> m = new HashMap <String, List <String> (); </span> as the length and complexity of type parameters increase, this lengthy specification quickly becomes painful. However, when using a static factory, the compiler can calculate the type parameter for you. This is type inference ). [Example] assume that HashMap provides the following static Factory: [java] <span style = "color: #333333;"> public static <K, V> HashMap <K, v> newInstance () {return new HashMap <K, V> () ;}</span> then you can replace the lengthy statement with the following concise form: <span style = "color: #333333;"> Map <String, List <String> m = HashMap. newInstance (); </span> this type of derivation can be performed one day when Java constructs function calls and method calls, but JDK1.6 cannot. Unfortunately, there is no factory method in the standard set implementation (such as HashMap) of JDK1.6, but you can add these methods to your tool class. More importantly, you can provide such static factory in your own parameter class. Disadvantage 1: only static factory methods are provided. classes without public or protected constructor cannot be subverted. The same applies to non-public classes returned by the public static factory. For example, you cannot subclass the convenient implementation classes in the Collection framework. In this case, it encourages programmers to use compound instead of inheritance (Item16 ). Disadvantage 2: The static factory method is not easy to distinguish from other static methods. They are not as prominent as constructors in the API documentation, so it is difficult to find out how to instantiate the class if the class provides static factory methods instead of constructors. Maybe one day the Javadoc tool will notice the static factory method. At this stage, you can reduce this defect by labeling static factories in class or interface annotations and following common naming conventions. Some common static factory methods are named as follows: valueOf -- not strictly speaking, this method returns an instance with the same value as its method parameters. This static factory is actually a type conversion method. Of -- valueOf's concise form, which is popular with EnumSet (Item32. GetInstance -- returns an instance described by the method parameter, but it does not necessarily have the same value as the method parameter. In Singleton mode, if getInstance has no parameter, a unique instance is returned. NewInstance -- similar to getInstance, but newInstance ensures that every returned instance is different. GetType -- similar to getInstance, except that the factory method is used in another different class. Type indicates the Type of the object returned by the factory method. Www.2cto.com newType -- similar to newInstance, but used when the factory method is in another different class. Type indicates the Type of the object returned by the factory method. In short, static factory methods and public constructor methods are useful, and we need to understand their respective strengths. Generally, static factories are preferred, so the first response should be to consider using static factories rather than public constructors.