美文网首页
工厂模式

工厂模式

作者: 粽里寻她 | 来源:发表于2023-02-17 12:57 被阅读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();
        }
    }
    

    相关文章

      网友评论

          本文标题:工厂模式

          本文链接:https://www.haomeiwen.com/subject/isopdktx.html