先创建一个接口
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:11
* @Description:
*/
public interface Shape {
void draw();
}
创建这个接口的实现类
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:11
* @Description: 矩形类
*/
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("This a Rectangle objext");
}
}
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:14
* @Description:
*/
public class Square implements Shape{
@Override
public void draw() {
System.out.println("This is a Square object");
}
}
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:13
* @Description:
*/
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("This is a Circle object");
}
}
完事之后创建一个工厂类 用于创建对象的工厂 比如 有一个车的接口 实现类是 宝马 奥迪 奔驰 那么有一个工厂 而 宝马 奥迪 奔驰又各自不同个但是它们有共同的属性就是 轮胎啊 发动机啊 共有的这些 我们不需要去具体的关心它们之间有什么不一样的 就可以使用这个工厂模式去创建这些
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:15
* @Description:
*/
public class ShapeFactory {
public Shape getShapeFactory(String shapeType) {
if (shapeType == null || "".equals(shapeType)) {
return null;
} else if ("CIRCLE".equals(shapeType)) {
return new Circle();
} else if ("SQUARE".equals(shapeType)) {
return new Square();
} else if ("RECTANGLE".equals(shapeType)) {
return new Rectangle();
}
return null;
}
}
再写一个类来测试一下 看看是个怎么个事
/**
* @Auther: XiaoShe
* @DateTime: 2023/6/16 11:19
* @Description:
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShapeFactory("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShapeFactory("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShapeFactory("SQUARE");
shape3.draw();
Shape shape4 = shapeFactory.getShapeFactory(null);
System.out.println(shape4);
}
}
结果就是
This is a Circle object
This a Rectangle objext
This is a Square object
null
刚好和我们想的一样 这就是一个简单的工厂模式