Item 1: Consider static factory methods instead of constructors

A class can provide a public static factory method to return a instance of itself.

The simple way to see it: It just a method that returns an object, nothing special. How to implement the method is controlled by us. We can return the same cached object every time; we can also give back brand new object; we are free to choose any subclass object of the return type; we can add some ingenuity in the process of building and selecting the object.

Advantage:

  • When a class has overloaded constructors, we can replace the multiple constructors with static factory methods, and choose names to highlight their differences.

    • This technique can also be used to solve the problem that constructors have the same parameter types.
      public class Complex {
      private final float re;
      private final float im;
      
      private Complex(float re, float im) {
          this.re = re;
          this.im = im;
      }
      
      public static Complex valueOf(float re, float im) {
          return new Complex(re, im);
      }
      
      public static Complex valueOfPolar(float r, float theta) {
          return new Complex((float) (r * Math.cos(theta)), (float) (r * Math.sin(theta)));
      }
      
  • Static factory methods are not required to create a new object each time they’re invoked.

    • Static factory methods have the ability to return the same object from repeated invocations
    • Used in Singleton Pattern, Immutable class, instance-controlled classes
      public static Boolean valueOf (boolean b) {
            return b ? Boolean.TRUE : Boolean.FALSE;
        }
  • Static Factory methods can return an object of any subtype of their return type.

    • Help for hiding implementation classes. This technique is used in building interface-based frameworks.
    • In java Collections framework. There are 32 convenience implementation of the Collection interface. Nearly all of these implementations are exported via static factory methods in the noninstantiable class (java.util.Collections)
      java.util.Collections Source Code
       public class Collections {
       // Suppresses default constructor, ensuring non-instantiability.
      private Collections() {
      }
       public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
          return new UnmodifiableCollection<T>(c);
      }
      /**
       * @serial include
       */
      static class UnmodifiableCollection<E> implements Collection<E>, Serializable {}
      
       public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) {
          return new UnmodifiableMap<K,V>(m);
      }
      /**
       * @serial include
       */
      private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {}
      }

    Using such a static factory method requires the client to refer to the returned object by its interface rather than its implementation class, which is generally good practice.

    • The class of the returned object can vary from invocation to invocation depending on the values of the parameters to the static factory. The implementation can be easily swapped.
    • The class of the returned object need not even exist at the time the static factory method is written.
      Like in the Service Provider framework: in which multiple service providers implement a service, and the framework makes the implementations available to its clients.
      //Service interface
      public interface Service {
      }
      //Service provider interface
      public interface Provider {
        public abstract Service newSerive();
      }
      //Noneinstantiable class for service registration and access
      public class Services {
        private Services(){}
        //Map service names to service providers
        private static final Map<String, Provider> providers = new ConcurrentHashMap<>();
        public static final String DEFAUL_PROVIDER_NAME = "<def>"; 
        //Provider registration API
        pubilc static void registerDefaultProvider(Provider p) {
           registerProvider(DEFAUL_PROVIDER_NAME, p);
        }
        public registerProvider(String name, Provider p) {
           providers.put(name, p);
        }
        //Service access API
        pubilc static Service getService() {
           return getService(DEFAUL_PROVIDER_NAME );
        }
        public static Service getService(String name) {
           Provider p = providers.get(name);
           if (p == null) {
              throw new IllegalArgumentException("No provider registered with name: " + name);
           }
           return p.newService();
        }
      }

    Similar to Strategy Pattern

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REAdMe.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READme.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 、 1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看READmE.文件(md如有),本项目仅用作交流学习参考,请切勿用于商业用途。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值