1.1(设计模式)工厂模式

 工厂模式:

工厂模式通过工厂创建对象,用户无需注意内部细节,只需要调用工厂类,

将需要创建的类名称传递给工厂即可。

采用工程类创建,最后返回的是接口类型,所以只用关心接口,不用关心接口的具体实现类。

Shape接口

public interface Shape {
    public void draw();
}

实现Shape接口的具体类:

public class Circle implements Shape{

    @Override
    public void draw() {
        System.out.println("draw circle");
    }  
}
public class Rectangle implements Shape{

    @Override
    public void draw() {
        System.out.println("draw rectangle");
    }
}
public class Square implements Shape{

    @Override
    public void draw() {
        System.out.println("draw square");
    }
}

ShapeFactory工厂:

public class ShapeFactory {
    public Shape getShape(String shape) {//传递图像字符串,根据字符串判断并实例化对应对象
        if("circle".equals(shape)) {
            return new Circle();
        }else if("rectangle".equals(shape)) {
            return new Rectangle();
        }else if("square".equals(shape)) {
            return new Square();
        }
        return null;
    } 
}

Main调用ShapeFactory实例化对象

public class Main {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape circle = shapeFactory.getShape("circle"); 
        circle.draw();
    }
}
运行结果:
draw circle

ShapeFatory中采用if else,当工厂中类多了后采用if else不易于扩展,且代码结构复杂不好分析。

故将图形用枚举类型代替,结合switch代替if else.

图形枚举

public enum ShapeEnum {
    CIRCLE,RECTANGLE,SQUARE
}

ShapeFactory

public class ShapeFactory {
    public Shape getShape(ShapeEnum shape) {
        switch(shape) {
        case CIRCLE:       return new Circle();
        case RECTANGLE:    return new Rectangle();
        case SQUARE:    return new Square();
        default : try {//没有找到指定类型则抛出ClassNotFound异常
                throw new ClassNotFoundException();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    } 
}

Main

public class Main {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape circle = shapeFactory.getShape(ShapeEnum.CIRCLE); 
        circle.draw();
    }
}
运行结果:
draw circle

参考资料:

http://www.runoob.com/design-pattern/factory-pattern.html

原文地址:https://www.cnblogs.com/huang-changfan/p/10692258.html