构造器与工厂方法的差别

原文地址:http://leihuang.org/2014/11/09/Constructors-VS-Factory-Methods/


首先看以下两者在创建对象上的差别

// 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,比方单例模式。

构造函数时做不到这种,而静态工厂方法能够非常easy的做到。

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 !


转载于:https://www.cnblogs.com/lcchuguo/p/5344825.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值