Effective Java By Joshua Bloch: Item1 - Static Factory Method

后端 未结 6 622
猫巷女王i
猫巷女王i 2020-12-13 05:20

I am reading the Effective Java by Joshua Bloch and I have question about Item1 Static Factory Method.

Quote[Bloch, p.7]<

6条回答
  •  天命终不由人
    2020-12-13 05:36

    Let's say you have an interface called List and you want to use the static factory method to create different type of lists. You cannot define the static factory methods in the List interface because it's an interface. So what you have to do it have a class that return instances of classes that implement List

    public class ListFactory{
      private ListFactory(){}
      public static List makeArrayList(){...}
      public static List makeLinkedList(){...}
      public static List makeCrazyList(){...}
    }
    

    You cannot do this

    public interface List{
       public static List makeArrayList();
       public static List makeLinkedList();
       public static List makeCrazyList();
    }
    

    Since List is interface.

提交回复
热议问题