欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Create mode -- Factory method

程序员文章站 2022-03-14 13:50:44
...

1 工厂方法模式

Create mode -- Factory method

interface Shape{
        public void draw();
    }
    class Rectangle implements Shape{
        @Override
        public void draw() {
            System.out.println("Draw rectangle");
        }
    }
    class Square implements Shape{
        @Override
        public void draw() {
            System.out.println("Draw square");
        }
    }
    class ShapeFactory{
        public Shape productShape(String name){
            if (name.isEmpty()){
                return null;
            }
            if (name.equals("rectangle")){
                return new Rectangle();
            }else if(name.equals("square")){
                return new Square();
            }
            return null;
        }
    }
    public class Test{
        public static void main(String[] args){
            ShapeFactory shapeFactory = new ShapeFactory();
            Shape shape = shapeFactory.productShape("rectangle");
            shape.draw();
            Shape shape1 = shapeFactory.productShape("square");
            shape1.draw();
        }
    }