#1. Static factory for object creation
Java provides object creation using new keyword but sometimes that's not preferred way to create object. For example, in situation where you want to re-use already created object, we will use private constructor. In this scenario we can expose static factory methods to access object.
Below mentioned are some of the examples for static factory way of object creation.
Java provides object creation using new keyword but sometimes that's not preferred way to create object. For example, in situation where you want to re-use already created object, we will use private constructor. In this scenario we can expose static factory methods to access object.
Below mentioned are some of the examples for static factory way of object creation.
- static factory methods have name and so, object creation will be via meaning method name.
- static factory controls instance creation
- static factory can return the object of any subtype
public class CustomerService { private static final CustomerService customerService = new CustomerService(); private CustomerService(){ } /** * returning new instance every time. Nothing fancy here ... * @return */ public static CustomerService newInstance(){ return new CustomerService(); } /** * singleton pattern. everytime same instance * @return */ public static CustomerService getInstance(){ return customerService; } }
#2. Consider builder when faced with many constructor parameters
Situation where we need to create object with many parameters, it's worth considering Builder Pattern. Example shown below. Here even though we increate attributes of ProjectMetadata, it does not make ProjectMetadata creation clumsy.
package instances; /** * Created by pbhavsar on 12/21/15. */public class ProjectMetaData { private String projectTitle = ""; private String brand; public static class Builder{ private String projectTitle; private String brand; public Builder(String projectTitle){ this.projectTitle = projectTitle; } public Builder brand(String brand) { this.brand = brand; return this; } public ProjectMetaData build(){ return new ProjectMetaData(this); } } private ProjectMetaData(Builder builder){ this.projectTitle = builder.projectTitle; this.brand = builder.brand; } public static void main(String[] args) { ProjectMetaData metaData = new ProjectMetaData.Builder("title").brand("sfly").build(); System.out.println(metaData.brand); System.out.println(metaData.projectTitle); } }Builder pattern also make immutable instance. Consider builder pattern when no. of attributes for objects are handful.#3. Enforce singleton pattern with private constructorcreating private constructor and static method returning static final instance will ensurethat we have only once object during the life of application.#4.