// Java Factory Pattern Example
// Step 1: Create an interface
interface Shape {
    void draw();
}
// Step 2: Create concrete classes implementing the above interface
class Rectangle implements Shape {
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}
class Square implements Shape {
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}
class Circle implements Shape {
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}
// Step 3: Create a Factory to generate object of concrete class based on given information.
class ShapeFactory {
    // use getShape method to get object of type shape 
    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;
    }
}
// Step 4: Use the Factory to get objects of Concrete class/shape by passing an information such as type.
class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        // get an object of Circle and call its draw method.
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        // call draw method of Circle
        shape1.draw();
        // get an object of Rectangle and call its draw method.
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        // call draw method of Rectangle
        shape2.draw();
        // get an object of Square and call its draw method.
        Shape shape3 = shapeFactory.getShape("SQUARE");
        // call draw method of Square
        shape3.draw();
    }
}Shape 接口定义了一个 draw() 方法,所有具体的形状类(如 Rectangle, Square, Circle)都实现了这个接口。Rectangle, Square, 和 Circle 类分别实现了 Shape 接口,并提供了各自的 draw() 方法实现。ShapeFactory 类包含一个 getShape 方法,根据传入的字符串参数返回相应的形状对象。FactoryPatternDemo 类展示了如何使用工厂模式来获取不同类型的形状对象,并调用它们的 draw() 方法。通过这种方式,工厂模式可以将对象的创建逻辑封装在工厂类中,使得客户端代码不需要关心具体的对象创建过程,从而提高了代码的灵活性和可维护性。
上一篇:java 创建list
下一篇:java int的最大值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站