ObjectFactory
就是通过Factory建造一个Object,比如说DBConnectionFactory就是专门建造DBConnection的工厂
BuilderFactory
就是通过Factory建造一个Builder(就叫Builder模式),比如说DBBuilderFactory就是专门建造DBConnectionBuilder的工厂
PS: 工厂模式和建造者模式可以混用
简单的例子
第一步,创建一个interface
interface Cat
{
public void meow ();
}
This is a key point, and an important part of the Factory Pattern:
You define a base class type (or in this case an interface), and then have any number of subclasses which implement the contract defined by the base class.
第二步,实现一个实例Class(implement from interface)
class BlackCat implements Cat
{
public void meow()
{
System.out.println("I am a BlackCat");
}
}
class WhiteCat implements Cat
{
public void meow()
{
System.out.println("I am a WhiteCat");
}
}
第三步,The Java Factory class
class CatFactory
{
public static Cat getCat(String criteria)
{
if ( criteria.equals("white") )
return new WhiteCat();
else if ( criteria.equals("black") )
return new BlackCat();
return null;
}
}
第四步,测试
public class JavaFactoryPatternExample
{
public static void main(String[] args)
{
Cat cat = CatFactory.getCat("white");
cat.meow();
}
}
想要看到更多玮哥的学习笔记、考试复习资料、面试准备资料?想要看到IBM工作时期的技术积累和国外初创公司的经验总结?
image敬请关注:
网友评论