简介
工厂模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
实际应用场景
1、日志记录器:记录可能记录到本地硬盘、系统事件、远程服务器等,用户可以选择记录日志到什么地方。
2、数据库访问,当用户不知道最后系统采用哪一类数据库,以及数据库可能有变化时。
3、设计一个连接服务器的框架,需要三个协议,“POP3”、“IMAP”、“HTTP”,可以把这三个作为产品类,共同实现一个接口。
UML
代码实现
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println(this.getClass().getName());
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println(this.getClass().getName());
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println(this.getClass().getName());
}
}
public class ShapeFactory {
public Shape getShepe(String shapeType) {
Shape shape = null;
if (Square.class.getSimpleName().equalsIgnoreCase(shapeType)) {
shape = new Square();
} else if (Circle.class.getSimpleName().equalsIgnoreCase(shapeType)) {
shape = new Circle();
} else if (Rectangle.class.getSimpleName().equalsIgnoreCase(shapeType)) {
shape = new Rectangle();
} else {
throw new RuntimeException("没有找到对应的类型");
}
return shape;
}
}
public class Main {
public static void main(String[] args) {
Shape shepe;
ShapeFactory factory = new ShapeFactory();
shepe = factory.getShepe(Square.class.getSimpleName());
shepe.draw();
shepe = factory.getShepe(Rectangle.class.getSimpleName());
shepe.draw();
shepe = factory.getShepe(Circle.class.getSimpleName());
shepe.draw();
}
}