在Java中工厂模式是最常用的模式之一,提供了一种非常好的创建对象的的方法,因此可以将这种模式归类于创建型模式。在工厂模式中,用户可以很容易地创建对象而不需要知道内在的逻辑,可以使用通用的接口引用创建的对象。
本例中创建一个Shape类型的接口,和Cricle, Square, Rectangle实现的类,创建一个ShapeFactory工厂类,示例通过向ShapeFactory中传递(CIRCLE/RECTANGLE/SQUARE)调用ShapeFactory获得相应的Shape对象。
创建一个Shape类型的接口
public interface Shape {
public void draw();
}
创建三个实现该接口的类
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Inside Ractangle::draw() method.");
}
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
创建工厂类
public class ShapeFactory {
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();
}
return null;
}
}
调用工厂类
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
输出:
Inside Circle::draw() method.
Inside Ractangle::draw() method.
Inside Square::draw() method.