简单工厂模式是由一个工厂对象决定创建出哪一种产品实例的方式。
一个形状接口
package pattern.creational.factory;
/**
* 形状 接口
*
* @author 吴尚慧
* @since 2022/6/13 10:21
*/
public interface Shape {
/**
* 画
*/
void draw();
}
形状实现类
圆
package pattern.creational.factory;
/**
* 圆
*
* @author 吴尚慧
* @since 2022/6/13 10:22
*/
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("画一个圆");
}
}
长方形
package pattern.creational.factory;
/**
* 长方形
*
* @author 吴尚慧
* @since 2022/6/13 10:22
*/
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("画一个长方形");
}
}
正方形
package pattern.creational.factory;
/**
* 正方形
*
* @author 吴尚慧
* @since 2022/6/13 10:22
*/
public class Square implements Shape {
@Override
public void draw() {
System.out.println("画一个正方形");
}
}
形状工厂
package pattern.creational.factory;
/**
* 形状工厂
*
* @author 吴尚慧
* @since 2022/6/13 10:24
*/
public class ShapeFactory {
/**
* 使用 getShape 方法获取形状类型的对象
*
* @param shapeType 形状类型
* @return 形状对象
*/
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;
}
}
工厂模式 demo
package pattern.creational.factory;
/**
* 工厂模式 demo
*
* @author 吴尚慧
* @since 2022/6/13 10:26
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//获取 Circle 的对象,并调用它的 draw 方法
Shape shape1 = shapeFactory.getShape("circle");
//调用 Circle 的 draw 方法
shape1.draw();
//获取 Rectangle 的对象,并调用它的 draw 方法
Shape shape2 = shapeFactory.getShape("rectangle");
//调用 Rectangle 的 draw 方法
shape2.draw();
//获取 Square 的对象,并调用它的 draw 方法
Shape shape3 = shapeFactory.getShape("square");
//调用 Square 的 draw 方法
shape3.draw();
}
}
结果:
画一个圆
画一个长方形
画一个正方形
参考:
https://www.runoob.com/design-pattern/design-pattern-intro.html