Consider providing static factory methods insteads of constructors

后端 未结 5 1303
清酒与你
清酒与你 2020-12-06 08:38

The normal way for a class to allow a client to obtain an instance is to provide a public contructor. Another way to do that is providing a public static factory method, whi

5条回答
  •  佛祖请我去吃肉
    2020-12-06 09:16

    One of the advantages is you can give the factory methods understandable names. It will help you easy to understand what function's work in your function and easy to maintain your code in the future. Take a look for this example, hope that it will help you.

        public class Contact {
    
        private Contact(String displayName, String phoneNumber, int contactType){
        //do something
        }
    
        //then we will have few functon static to get constructor private
        public static createContactUnknow(String phoneNumber){
            return new Contact("","00000000",0);
        }
    
        public static createContactValid(String displayName, String phoneNumber, int contactType){
            return new Contact(displayName, phoneNumber, contactType);
        }
    }
    
        //then
        Contact myGirlFriend = Contact.createContactValid("xxxx","000000",1);
        Contact unknowFriend = Contact.createContactUnknow("45454545");
    

提交回复
热议问题