Java 设计模式结构如下:
工厂模式包括:静态工厂模式,工厂方法模式,抽象工厂模式。
在工厂模式中,我们创建对象时不会对客户端暴露出创建逻辑,而是通过使用一个共同的接口来指向新创建的对象。
1. 静态工厂模式
静态工厂模式,也叫做简单工厂模式,是工厂模式中最简单的一个模式。由一个工厂类对象决定创建出哪种产品类的实例。
实现:创建一个 Shape 接口和实现 Shape 接口的实体类,再创建一个工厂类 ShapeFactory,通过工厂类中方法创建出不同类型的对象。
(1)创建 Shape 接口
public interface Shape {
void draw();
}
(2)创建实现类
public class CircleShape implements Shape {
@Override
public void draw() {
System.out.println("Circle draw()");
}
}
public class SquareShape implements Shape {
@Override
public void draw() {
System.out.println("SquareShape draw()");
}
}
public class RectangleShape implements Shape {
@Override
public void draw() {
System.out.println("Rectangle draw()");
}
}
(3) 创建工厂类
public class ShapeFactory {
public static Shape createShape(int type) {
Shape shape = null;
if (type == 1) {
shape = new CircleShape();
} else if (type == 2) {
shape = new RectangleShape();
}
return shape;
}
}
(4) 客户端调用
public class MainApp {
public static void main(String[] argbs) {
Shape shape = ShapeFactory.createShape(1);
shape.draw();
shape = ShapeFactory.createShape(2);
shape.draw();
}
}
工厂类也可以通过反射进行获取实体对象,避免了通过参数 type 进行判断处理。
public class ShapeFactory {
public static Shape createShape(Class<? extends Shape> clazz) {
try {
Shape shape = clazz.newInstance();
return shape;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
public class MainApp {
public static void main(String[] argbs) {
Shape shape = ShapeFactory.createShape(CircleShape.class);
shape.draw();
shape = ShapeFactory.createShape(RectangleShape.class);
shape.draw();
}
}
2. 工厂方法模式
当需要增加其他的 Shape类型时,需要增加相应的工厂类,使得代码类成倍增加。
(1) Shape 接口
public interface Shape {
void draw();
}
(2) Shape 接口实现类
public class CircleShape implements Shape {
@Override
public void draw() {
System.out.println("Circle draw()");
}
}
public class SquareShape implements Shape {
@Override
public void draw() {
System.out.println("SquareShape draw()");
}
}
public class RectangleShape implements Shape {
@Override
public void draw() {
System.out.println("Rectangle draw()");
}
}
(3) 工厂接口类
public interface ShapeMethodFactory {
Shape createShape();
}
(4) 工厂接口实现类
public class CircleShapeFactory implements ShapeMethodFactory {
@Override
public Shape createShape() {
return new CircleShape();
}
}
public class RectangleShapeFactory implements ShapeMethodFactory {
@Override
public Shape createShape() {
return new RectangleShape();
}
}
public class SquareShapeFactory implements ShapeMethodFactory {
@Override
public Shape createShape() {
return new SquareShape();
}
}
(5) 客户类
public class MainApp {
public static void main(String[] argbs) {
ShapeMethodFactory factory = new CircleShapeFactory();
Shape shape = factory.createShape();
shape.draw();
factory = new SquareShapeFactory();
shape = factory.createShape();
shape.draw();
}
}