工厂模式
参考 W3c School
工厂模式属于 创建型 设计模式
作用:想要一个对象,调用工厂对象,调用方法直接输入对象的名字即可。
例如:找文具厂获取文具【笔记本】,调用完成后,工厂将笔记本对象给你,封装了后面的细节。
目录
UML类图
首先我们来写接口:
接口Shape
public interface Shape {
/**
* 绘制图形方法
*/
public abstract void draw();
}
创建三个实体类:Circle Square Rectangle
Circle
public class Circle implements Shape {
/**
* 绘制圆形
*/
@Override
public void draw() {
System.out.println("[Circle] Draw");
}
}
Square
public class Square implements Shape {
/**
* 绘制矩形
*/
@Override
public void draw() {
System.out.println("[Square] Draw");
}
}
Rectangle
public class Rectangle implements Shape {
/**
* 绘制三角形
*/
@Override
public void draw() {
System.out.println("[Rectangle] Draw");
}
}
创建存储对象字符串的常量类
ShapType
public class ShapeType {
public static final String CIRCLE = "circle";
public static final String RECTANGLE = "rectangle";
public static final String SQUARE = "square";
}
创建工厂类
ShapeFactory
public class ShapeFactory {
public Shape getShape(String shapeType){
/* 判断字符串非空 */
if (shapeType == null){
return null;
}
/* 匹配输入的字符串,生成对象 */
if (CIRCLE.equalsIgnoreCase(shapeType)){
return new Circle();
}else if (RECTANGLE.equalsIgnoreCase(shapeType)){
return new Rectangle();
}else if (SQUARE.equalsIgnoreCase(shapeType)){
return new Square();
}
/* 没有相关对象,返回空对象 */
return null;
}
}
Main
创建 Main 入口的测试执行类
public class ExecuteMain {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
Shape rectangle = shapeFactory.getShape("rectangle");
Shape square = shapeFactory.getShape("square");
Shape unKnown = shapeFactory.getShape("unknown");
circle.draw();
rectangle.draw();
square.draw();
System.out.println(unKnown==null);
}
}
运行
[Circle] Draw
[Rectangle] Draw
[Square] Draw
true
Process finished with exit code 0
可以看到,工厂中存在的类型能创建出相对应的对象,而不存在的类型将返回 null 。