简单工厂模式 (Simple Factory Pattern)


   简单工厂模式有一个中心的工厂类,它负责所有产品的创建。显然它足够简单,至少完成了“对象的创建与使用分离”这一任务,但是它又违反了开闭原则这个面向对象关键性的原则,如果要引入新的产品,就要对工厂类的内部代码进行修改。

public class Main {
    
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        shape1.draw();
   
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        shape2.draw();
   
        Shape shape3 = shapeFactory.getShape("SQUARE");
        shape3.draw();
    }
}

class ShapeFactory {
    
    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;
    }
}

interface Shape {
    void draw();
}

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