Effective Java -> (1) Creating and destroying objects

xiaoxiao2021-03-05  24

Effective Java Learning Notes Java Language supports four basic types: interface, class (Class), Array, and primitive types (Primitive). The first three types are often referred to as reference types, an instance of the class and an array is an object (Object), and the value of the primitive type is not an object. A member of a class includes its domain (METHOD), Member Class, and member interface. The prototype of a method includes its name and all types of reference, and the prototype does not include its return type.

Article 1: Consider replacing the constructor with a static factory method for a class, in order to obtain an example, the most common method is to provide a public constructor New one. Another method is to provide an instance of a class by providing a static factory method, it returns an instance of classes. Below is a static method in the Singleton mode, and the unique example of the class is returned. Public static a getInstance () {return instance;}

Benefits of static factory methods: (1) The static method has the name. If the parameters of a constructor do not exactly describe the returned objects, select a static factory that uses the appropriate name to make a class easier to use, and the corresponding customer code is easier to read. (2) The static method is not required to create a new object when it is called. Static factory methods can return the same object for duplicate calls. (For example, a Singleton mode) (3) The static method can return an object of a sub-type of the original return type. (This is often used in an interface-based frame structure, and abstract factory model, there is a java.util.collections class in Java's Collections Framework, there are many useful static methods, which is referenced by returning the interface. An example of a hidden implementation class).

Main Disadvantages of Static Factory Method: (1) If the class does not contain public or protected constructors, it cannot be subclassified. (Encourage the use of composite structures rather than inheritance) (2) There is no difference from other static methods. Where [Valueof] is generally a type conversion operation, the name [getInstance] method returns an instance. Summary: Static factory methods and public constructor have their own use, understand the structure of their respective strengths to more reasonable design.

转载请注明原文地址:https://www.9cbs.com/read-35477.html

New Post(0)