设计模式—工厂模式

介绍

代码

接口

创建 Shape 接口

public interface Shape {
    void draw();
}

实现类

创建 Shape 接口的三个实现类:CirleRectangleSquare

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Circle");
    }
}
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Rectangle");
    }
}
public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Square");
    }
}

工厂类

创建工厂类,用于生产指定类型的 Shape

public class ShapeFactory {
    public Shape getShape(String type) {
        if(type == null){
            return null;
        }

        if(type.equalsIgnoreCase("Circle")) {
            return new Circle();
        }
        if(type.equalsIgnoreCase("Rectangle")) {
            return new Rectangle();
        }
        if(type.equalsIgnoreCase("Square")) {
            return new Square();
        }

        return null;
    }
}

测试

public class FactoryTest {
    @Test
    void test() {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape circle = shapeFactory.getShape("Circle");
        Assertions.assertEquals(circle.getClass(), Circle.class);
        circle.draw();

        Shape rectangle = shapeFactory.getShape("Rectangle");
        Assertions.assertEquals(rectangle.getClass(), Rectangle.class);
        rectangle.draw();

        Shape square = shapeFactory.getShape("Square");
        Assertions.assertEquals(square.getClass(), Square.class);
        square.draw();
    }
}
posted @ 2023-12-23 12:36  Frodo1124  阅读(12)  评论(0编辑  收藏  举报