Create mode -- Factory method

1 工厂方法模式

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();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_28197211/article/details/80775021
今日推荐