构造器与工厂方法的差别
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了构造器与工厂方法的差别相关的知识,希望对你有一定的参考价值。
原文地址: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 !
以上是关于构造器与工厂方法的差别的主要内容,如果未能解决你的问题,请参考以下文章