1.简单工厂模式
工厂方法模式定义了一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
2.类图
Shape 接口
public interface Shape {
void draw();
}
Circle 类
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape-Circle");
}
}
Rectangle类
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape-Rectangle");
}
}
ShapeFactory类
public class ShapeFactory {
public Shape getShape(String shapeType) {
if(shapeType == null)
return null;
else if(shapeType.equalsIgnoreCase("circle"))
return new Circle();
else if(shapeType.equalsIgnoreCase("rectangle"))
return new Rectangle();
else if(shapeType.equalsIgnoreCase("square"))
return new Square();
else
return null;
}
}
Main类
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
circle.draw();
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw();
Shape square = shapeFactory.getShape("square");
square.draw();
}
}
2. 简单工厂模式的优点
- 实现对象的创建和对象的使用分离,将对象的创建交给专门的工厂类负责
- 客户端无需知道所创建的具体产品类的雷鸣,只需要知道具体产品类所对应的参数即可
3. 简单工厂模式的缺点
- 简单工厂类不够灵活,增加新的具体产品需要修改工厂类的判断逻辑,当产品较多时,工厂方法的代码逻辑较为复杂
- 系统扩展较为困难,一旦增加新产品就不得不修改工厂逻辑,破坏了“开闭原则”
4. 简单工厂模式的适用环境
复杂对象适合使用工厂模式,简单对象,尤其是仅需要通过new
就可以完成创建的对象,不需要使用工厂模式,因为工厂模式需要引入一个工厂类,增加系统的复杂度。
JDBC中的工厂方法
Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=DB;user=sa;password=");
Statement statement=conn.createStatement();
ResultSet rs=statement.executeQuery("select * from UserInfo");
5. 参考并感谢
[1] https://www.runoob.com/design-pattern/factory-pattern.html
[2] https://www.jianshu.com/p/5cb52d84bd6d