静态工厂方法介绍
它只是一个简单的静态方法,返回类的一个实例.1. 与构造函数不同,静态工厂方法具有名字.选用适当名字的静态工厂方法可以使一个类更易于使用,并且相应的客户代码更易于阅读.
2. 与构造函数不同,不要求非得创建一个新的对象.这使得一些非可变类可以使用一个预先构造好的实例,或者把已经构造好的实例缓冲起来.同时,静态工厂方法可以为重复的调用返回同一个对象,这也可以被用来控制"在某一时刻哪些实例应该存在." 好处1:使得一个类可以保证是一个singleton. 好处2:使非可变类可以保证"不会有两个相等的实例存在",即当且仅当a==b时才有a.equals(b)为true.这可以提高性能.
3. 与构造函数不同,它们可以返回一个原返回类型的子类型的对象.特别是,能够返回实现类对于调用者隐藏的对象.这项技术非常适合于基于接口的框架结构,因为这样的框架结构中,接口成为静态工厂方法的自然返回类型.调用者只能通过接口来引用被返回的对象,而不能通过实现类来引用被返回的对象.
静态工厂方法的命名包括getInstance和valueOf,但这并不是强制要求的,只要具有明确的意义即可.
示例:
publicclassComplexNumber{
/**
*Staticfactorymethodreturnsanobjectofthisclass.
*/
publicstaticComplexNumbervalueOf(floataReal,floataImaginary){
returnnewComplexNumber(aReal,aImaginary);
}
//privateconstructorpreventssubclassing
privateComplexNumber(floataReal,floataImaginary){
fReal=aReal;
fImaginary=aImaginary;
}
privatefloatfReal;
privatefloatfImaginary;
}
/**
*Staticfactorymethodreturnsanobjectofthisclass.
*/
publicstaticComplexNumbervalueOf(floataReal,floataImaginary){
returnnewComplexNumber(aReal,aImaginary);
}
//privateconstructorpreventssubclassing
privateComplexNumber(floataReal,floataImaginary){
fReal=aReal;
fImaginary=aImaginary;
}
privatefloatfReal;
privatefloatfImaginary;
}
JDK2中的示例:
LogManager.getLogManager
publicstaticLogManagergetLogManager(){
if(manager!=null){
manager.readPrimordialConfiguration();
}
returnmanager;
}
if(manager!=null){
manager.readPrimordialConfiguration();
}
returnmanager;
}
Pattern.compile
publicstaticPatterncompile(Stringregex){
returnnewPattern(regex,0);
}
returnnewPattern(regex,0);
}
Collections.unmodifiableCollection, Collections.synchronizeCollection等等
publicstatic<T>Collection<T>unmodifiableCollection(Collection<?extendsT>c){
returnnewUnmodifiableCollection<T>(c);
}
publicstatic<T>Collection<T>synchronizedCollection(Collection<T>c){
returnnewSynchronizedCollection<T>(c);
}
returnnewUnmodifiableCollection<T>(c);
}
publicstatic<T>Collection<T>synchronizedCollection(Collection<T>c){
returnnewSynchronizedCollection<T>(c);
}
Calendar.getInstance
publicstaticCalendargetInstance(){
Calendarcal=createCalendar(TimeZone.getDefaultRef(),Locale.getDefault());
cal.sharedZone=true;
returncal;
}
Calendarcal=createCalendar(TimeZone.getDefaultRef(),Locale.getDefault());
cal.sharedZone=true;
returncal;
}
与reflection一起作用:
对象实例可以由user input,config file,或者任意来源决定.
完全支持在runtime时决定需要的对象实例.
publicclassCreator{
//#1:basicstaticfactorymethod
protectedstaticHellocreateHelloer(){
returnnewHelloWorld();
}
//#2:parametedstaticfactorymethod
protectedfinalstaticintWORLD=1;
protectedfinalstaticintCAMEL=2;
protectedstaticHellocreateHelloer(intid){
if(id==1){
returnnewHelloWorld();
}
if(id==2){
returnnewHelloCamel();
}
returnnull;
}
//#3:usereflection
protectedstaticHellocreateHelloer(Stringname){
try{
Classc=Class.forName(name);
return(Hello)c.newInstance();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}catch(InstantiationExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
returnnull;
}
publicstaticvoidmain(String[]args){
/*
*nofactorymethod,usualcodes
*/
HelloWorldhw=newHelloWorld();
hw.sayHello();
HelloCamelhc=newHelloCamel();
hc.sayHello();
System.out.println("===========================");
/*
*basicfactorymethod
*
*fordifferentrequirement,youcannewdifferentsubclassand
*overridecreateHelloer()togetdedicatedimplementedclass
*/
Helloh=createHelloer();
h.sayHello();
System.out.println("===========================");
/*
*parametedfactorymethod
*/
h=createHelloer(WORLD);
h.sayHello();
h=createHelloer(CAMEL);
h.sayHello();
/*
*parametedfactorymethodbyreflection
*/
System.out.println("===========================");
h=createHelloer("HelloWorld");
h.sayHello();
h=createHelloer("HelloCamel");
h.sayHello();
}
}
interfaceHello{
voidsayHello();
}
classHelloWorldimplementsHello{
publicvoidsayHello(){
System.out.println("Hello,World!");
}
}
classHelloCamelimplementsHello{
publicvoidsayHello(){
System.out.println("Hello,Camel");
}
}
//#1:basicstaticfactorymethod
protectedstaticHellocreateHelloer(){
returnnewHelloWorld();
}
//#2:parametedstaticfactorymethod
protectedfinalstaticintWORLD=1;
protectedfinalstaticintCAMEL=2;
protectedstaticHellocreateHelloer(intid){
if(id==1){
returnnewHelloWorld();
}
if(id==2){
returnnewHelloCamel();
}
returnnull;
}
//#3:usereflection
protectedstaticHellocreateHelloer(Stringname){
try{
Classc=Class.forName(name);
return(Hello)c.newInstance();
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}catch(InstantiationExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
returnnull;
}
publicstaticvoidmain(String[]args){
/*
*nofactorymethod,usualcodes
*/
HelloWorldhw=newHelloWorld();
hw.sayHello();
HelloCamelhc=newHelloCamel();
hc.sayHello();
System.out.println("===========================");
/*
*basicfactorymethod
*
*fordifferentrequirement,youcannewdifferentsubclassand
*overridecreateHelloer()togetdedicatedimplementedclass
*/
Helloh=createHelloer();
h.sayHello();
System.out.println("===========================");
/*
*parametedfactorymethod
*/
h=createHelloer(WORLD);
h.sayHello();
h=createHelloer(CAMEL);
h.sayHello();
/*
*parametedfactorymethodbyreflection
*/
System.out.println("===========================");
h=createHelloer("HelloWorld");
h.sayHello();
h=createHelloer("HelloCamel");
h.sayHello();
}
}
interfaceHello{
voidsayHello();
}
classHelloWorldimplementsHello{
publicvoidsayHello(){
System.out.println("Hello,World!");
}
}
classHelloCamelimplementsHello{
publicvoidsayHello(){
System.out.println("Hello,Camel");
}
}
----------------------------------------------
作者: nirvana_li
日期:06-09-05
本文地址:http://www.45fan.com/dnjc/69975.html