Effective Java By Joshua Bloch: Item1 - Static Factory Method

后端 未结 6 639
猫巷女王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:35

    1. Interfaces cant have static methods, so by convention, static factory methods for an interface named Type are put in non-instantiable class named Types.

      The point is just the plural 's' on "Type[s]". So if your interface is called Foo and you want to create some implementation called MyFoo then your factory with the methods to instantiate should be called Foos by convention.

    2. The classes of the returned objects are all non-public

      This means that the classes of objects returned from the factory methods have a private or default visibility modifier as in private class MyFoo{} so that they can not be instantiated by any other means but their factory methods. Since you can't construct an Object using the new operator from private inner or package private class out of their scope (reflection aside).

    e.g.:

     public interface Foo{ //interface without plural 's' (question 1)
         public void bar();
     }
     public abstract class Foos(){ // abstract factory with plural 's' (question 1)
        public static Foo createFoo(){
            return new MyFoo();
        }
        private class MyFoo implements Foo{ // a non visible implementation (question 2)
           public void bar(){}
        }
     }
    

提交回复
热议问题