工厂模式是java设计模式中被使用最多的一种设计模式。它是一种叫做创建型模式(creational pattern)的大类中的一种设计模式,它提供了一种创建对象的最好的方法。
在工厂模式中,我们在不将创建对象的具体逻辑暴露给客户端(client)的情况下来创建一个对象实例,然后通过使用公共的接口将新创建的对象实例返回给调用该接口的客户端。
具体实现
我们将创建一个叫做Shape的接口,然后用一个类实现这个接口。接着创建一个叫做ShapeFactory的工厂类。最后我们创建一个叫做FactoryPatternDemo的样例类,我们将在样例类中使用ShapeFactory 来获取Shapeobject。样例将传递信息(CIRCLE / RECTANGLE / SQUARE)给ShapeFactory 以得到她所需要的对象类型。
第一步:创建一个接口
Shape.java
package com.patterns.factory;
public interface Shape {
void draw();
}
第二步:创建相关的一些类来实现 Shape 接口
Rectangle.java
package com.patterns.factory;
public class Rectangle implements Shape{
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
package com.patterns.factory;
public class Square implements Shape{
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
package com.patterns.factory;
public class Circle implements Shape{
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
第三步:创建一个工厂类,好根据输入的信息生成相关的类的对象实例
ShapeFactory.java
package com.patterns.factory;
public class ShapeFactory {
//use getShape method to get object of type shape
public Shape getShape(String shapeType){
if(shapeType ==null)
{
return null;
}
if(shapeType.equalsIgnoreCase("circle"))
{
return new Circle();
}else if(shapeType.equalsIgnoreCase("rectangle"))
{
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("square"))
{
return new Square();
}else{
return null;
}
}
}
第四步:使用Factory 的方法getShape获取对象实例,类型信息将作为参数传入给方法getShape,以决定将要获取哪种class类型的对象
FactoryPatternDemo.java
package com.patterns.factory;
public class FactoryPatternDemo {
public static void main(String[] args){
ShapeFactory shapeFacotry = new ShapeFactory();
Shape shape1 = shapeFacotry.getShape("rectangle");
shape1.draw();
Shape shape2 = shapeFacotry.getShape("circle");
shape2.draw();
Shape shape3 = shapeFacotry.getShape("square");
shape3.draw();
}
}
第五步:验证输出
Inside Rectangle::draw() method.
Inside Circle::draw() method.
Inside Square::draw() method.