静态工厂模式

mesum 2008-04-14 09:29:56
我的网址:www.javaedu.com.cn

QQ:2535279


所谓静态工厂方法,就是返回类的一个实例的静态方法.
静态工厂方法的优点是:
1.静态工厂方法具有名字
2.每次被调用的时候不要求非得创建一个新的对象.
3.可以返回一个原返回类型的子类型的对象
静态工厂方法的缺点是:
1.类如果不含公有的或者受保护的构造函数就不能被子类化
2.比其他静态方法没有区别,不能标志它们的特殊性

闲话少叙,我们来看看静态工厂方法怎么来实现.我们来举个例子:


public class Cat{

private String name;
private String color;
private String host;


/* ......
getter/setter方法
*/

public Cat(){
}

public Cat(String name,String color,String host){

this.name = name;
this.color = color;
this.host = host;
}

//知道名字,颜色和主人名字的时候调用的静态方法
public static Cat getCatwithFullinfo(String name,String color,String host){

return new Cat(name,color,host);
}

//不知道任何信息的时候调用的静态方法
public static Cat getCat(){

return new Cat();
}

//只知道名字的时候调用的静态方法
public static Cat getCatwithName(String name){

return new Cat(name,"","");
}

//只知道颜色的时候调用的静态方法
public static Cat getCatwithColor(String color){

return new Cat("",color,"");
}

//只知道主人名字的时候调用的静态方法
public static Cat getCatwithHost(String host){

return new Cat("","",host);
}

//知道名字和颜色的时候调用的静态方法
public static Cat getCatwithNameColor(String name,String color){

return new Cat(name,color,"");
}

//知道名字和主人名字的时候调用的静态方法
public static Cat getCatwithNameHost(String name,String host){

return new Cat(name,"",host);
}

//知道颜色和主人名字的时候调用的静态方法
public static Cat getCatwithColorHost(String color,String host){

return new Cat("",color,host);
}


}

使用静态工厂方法时,可以在知道的信息不完整的情况下,找到适合的构造方法.

...全文
446 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangshikang_it 2008-04-14
  • 打赏
  • 举报
回复
学习咯!!!!!!!!!

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧