首页 > 代码库 > 构造器与工厂方法的区别

构造器与工厂方法的区别


首先看下面两者在创建对象上的区别

// instantiating a class using constructor
Dog dog = new Dog(); 

// instantiating the class using static method
Class Dog{
  private Dog(){
  }
  // factory method to instantiate the class
  public static Dog getInstance(){
    return new Dog();
  }
}

下面谈谈静态工厂方法的优缺点:

优点:

1.静态工厂方法有名字而构造函数没有

因为工厂方法可以有多个,通过名字来区别各个方法,但构造函数名字只能有一个,只能通过参数来区别,所以使用静态工厂方法更明了。

2.静态工厂方法支持条件性实例化

就是说你创建对象时,有时需要添加一些条件判断是否应该创建,如果满足条件则返回一个实例,不满足则返回NULL,比如单例模式。构造函数时做不到这样的,而静态工厂方法可以很简单的做到。

3.方法能够返回返回类型的子类型

Suppose there is a class Animal and it has subclass Dog. We have static method with signature

  public static Animal getInstance(){

  }

then method can return Both objects of type Animal and Dog which provides great flexibility.

缺点:

1.If constructor of the class is not public or protected then the class cannot be sub classed

如果一个类只能通过静态工厂方法来获得实例,那么该类的构造函数就不能是共有的或受保护的,那么该类就不会有子类,即该类不能被继承。单例模式中首先要私有化构造器

2.静态工厂方法和其他静态方法从名字上看无法区分

下面就是静态工厂方法常用的命名

valueOf —Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods.

of —A concise alternative to valueOf , popularized by EnumSet

getInstance —Returns an instance that is described by the parameters but cannot be said to have the same value. In the case of a singleton, getInstance takes no parameters and returns the sole instance.

newInstance —Like getInstance , except that newInstance guarantees that each instance returned is distinct from all others.

getType—Like getInstance , but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.

newType—Like newInstance , but used when the factory method is in a different class. Type indicates the type of object returned by the factory method.


2014-11-09 14:39:17

Brave,Happy,Thanksgiving !


构造器与工厂方法的区别