工厂模式

2023-02-17  本文已影响0人  粽里寻她

工厂模式作为Java最常见的设计者模式之一,属于创建型模式,它提供了一种创建对象的最佳方式。
工厂模式:我们创建对象不会暴露如何实现的逻辑, 并且使用同一个的接口指向新的创建对象。
工厂模式

public interface Shape {
    void draw();
}

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

public enum ShapeType {
    RECTANGLE, SQUARE, CIRCLE;
}

public class ShapeFactory {
    public Shape getShape(ShapeType shapeType) {
        switch (shapeType) {
            case RECTANGLE:
                return new Rectangle();
            case SQUARE:
                return new Square();
            case CIRCLE:
                return new Circle();
            default:
                throw new IllegalArgumentException("Unknown shape type: " + shapeType);
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        Shape rectangle = shapeFactory.getShape(ShapeType.RECTANGLE);
        rectangle.draw();

        Shape square = shapeFactory.getShape(ShapeType.SQUARE);
        square.draw();

        Shape circle = shapeFactory.getShape(ShapeType.CIRCLE);
        circle.draw();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读